Java generate file name

Generating UUIDs for file names in Java

The inquiry is about generating a random file name in the format of «Type-random», where Type is a String. The provided code doesn’t work, and two solutions are suggested. One option is to use the random function in JDK to generate a UUID. Alternatively, the date time can be generated from calendar/joda and concatenated with the string, or string buffers can be used before converting to a string.

Unique File name using system time in Java?

How can I generate unique IDs for files using system time in Java?

The class you are searching for is identified as UUID .

UUID class is what you need.

An example of how to implement this can be seen below.

public class RandomStringUUID < public static void main(String[] args) < UUID uuid = UUID.randomUUID(); String randomUUIDString = uuid.toString(); System.out.println("Random UUID String = " + randomUUIDString); System.out.println("UUID version = " + uuid.version()); System.out.println("UUID variant = " + uuid.variant()); >> 
Random UUID String = 7dc53df5-703e-49b3-8670-b1c468f47f1f UUID version = 4 UUID variant = 2 

I suggest utilizing File.createTempFile(String prefix, String suffix) to generate a blank file that does not intersect with any other files within the system.

To ensure its deletion upon program exit, File.deleteOnExit can be employed.

One option is to utilize the method System.currentTimeInMillis.

SerialVersionUID in Java, SerialVersionUID in Java. The serialization at runtime associates with each serializable class a version number called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to …

Generating a random file name in java

It is required of me to produce a name for random file in the specified format:

(Date time duration mob_no Type).wav 

The variables Date , time , duration , mob_no , and Type are random, while Type is a String type and the other variables are typical.

I attempted to utilize this code, but it’s not functioning.

public ArrayList randomFileName() throws ParseException < for (int i = 0; i < noOfSub; i++) < START_DATE.add(String.valueOf(theDay.getTime() - 360000000) + random.nextInt(9999900)); DURATION.add(random.nextInt(9)); A_NO.add(9000000000L + random.nextInt(999999999)); B_NO.add(1000000000L + random.nextInt(999999999)); >return fileName; > 

To obtain an arbitrary name, you may opt to employ the random feature in JDK, which generates a UUID on your behalf. Alternatively, you could generate the date and time using calendar/joda and merge the strings, or use string buffers, if feasible, and subsequently convert them to a string.

Utilizing the nextLong() from the Random class enables the production of a fresh data time stamp, which can be formatted to the preferred style through the use of a SimepleDateFormat . Additionally, generating duration and mob_no are two other numerical values options available.

Читайте также:  Http retracker local announce php

How to create user friendly unique IDs, UUIDs or other, Usecase: you want to send out IDs via Mail to your customers which in turn visit your site and enter that number into a form, like a voucher ID. I assume that UUIDs get generated equally through the whole range of the 128 Bit range of the UUID. So would it be sage to use just the lower 64 Bits for instance?

Returning the same generated UUID in a static and non-static method

I possess an entity that is characterized as follows:

The file named TestDriver.java needs to be considered.

public void TestDriver extends FirefoxDriver implements SupportDownloads < public TestDriver()< super(TestDriver.service(), TestDriver.options()); >private static service() < // implementation >private static options() < .. // attempting to generate a UUID which will be eventually be set as the folder where all downloads will go to. // unique paths are needed as we will be using this class for multi-threaded runs and would like each browser to have its own unique download folder byte[] value = String.valueOf(Thread.currentThread().getId()).getBytes()); String uniqueID = UUID.nameUUIDFromBytes(value).toString(); .. >// purpose of this method is to return the path download folder // note the repeated generation of the UUID because the above methods are static @Override public File getDownloadPath() < String value = String.valueOf(Thread.currentThread().getId()); return new File(prop.getProperty(fileDirectory()) + File.separator + UUID.nameUUIDFromBytes(value.getBytes())); >> 

Java file named SupportsDownload.java.

public interface SupportsDownload

What I am trying to do is:

  1. In order to ensure that every thread created has distinct download paths, a UUID needs to be generated.
  2. To make the UUID accessible outside of this class for unit-testing usage by users, it should also be returned in a public method.

Despite the functional state of the above code, there is a potential issue outlined in the official Java documentation.

This Thread provides an identifier, which is a unique positive long number generated at creation and remains unchanged throughout its lifetime. It’s important to note that if a thread is terminated, its thread ID may be reused.

The method mentioned earlier may not be entirely reliable since relying solely on Thread.currentThread().getId() to generate UUID seed could produce identical IDs if they are reused, resulting in a duplicated UUID.

I attempted to make a modification that involved the inclusion of time in milliseconds, specifically:

 byte[] value = String.valueOf(Thread.currentThread().getId() + Calendar.getInstance().getTimeInMillis()).getBytes()); 

Since the value of time is constantly fluctuating, it would be impossible for me to obtain the precise value again when using the return method. getDownloadPath() .

Assuming I create the time value only once and assign it to a variable, like this:

private final long timeInMillis = Calendar.getTime().getTimeInMillis();

This variable cannot be used in both static and non-static methods.

I’m in need of suggestions, any help would be appreciated 🙂

My recommendation for your task is to utilize ThreadLocal . A sample code has been provided below for your reference.

public class Main < public static void main(String[] args) < Thread t1 = new Thread(() ->< MyUUIDFactory.getUUIDPerThread(); MyUUIDFactory.getUUIDPerThread(); >, "My Thread-1"); Thread t2 = new Thread(() -> < MyUUIDFactory.getUUIDPerThread(); MyUUIDFactory.getUUIDPerThread(); >, "My Thread-2"); t1.start(); t2.start(); > > class MyUUIDFactory < private static final ThreadLocallocalWebDriver = ThreadLocal.withInitial( () -> UUID.randomUUID().toString()); public static String getUUIDPerThread() < return localWebDriver.get(); >> 

“uuid java example” Code Answer, Get code examples like «uuid java example» instantly right from your google search results with the Grepper Chrome Extension.

Set the UUID and User ID into the current request thread

Is it possible to access the current request thread and improve my production logging for the rest application?

  • Create a unique identifier for every request.
  • Get the username
  • Insert both the username and UUID within the thread.
Читайте также:  Java objects same hashcode

With the help of logging or jstack, I can easily access the specifics.

One option for utilizing Spring Security is to employ Spring’s SecurityContextHolder.

User user = (org.springframework.security.core.userdetails.User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String name = user.getUsername(); //get logged in username 

Subsequently, employ the JDK method to produce a UUID.

Utilizing thread local to store this information is not advisable; instead, it would be best to store it in the current http session. If a stateless session is used, the session provided by the auth server can be utilized, and the access token can be used to store the necessary data. It is worth noting that many auth services allow the creation of custom fields in the access token.

Java — Set the UUID and User ID into the current request, And then use JDK function for generating UUID. java.util.UUID.randomUUID() Updated. I would not recommend to use thread local for storing this info, ideally you could store this info in current http session. If you use stateless session you could use session provided by your auth server and …

Источник

How to Generate a Unique and Short File Name in Java

What is the best way to generate a unique and short file name in Java

Well, you could use the 3-argument version: File.createTempFile(String prefix, String suffix, File directory) which will let you put it where you’d like. Unless you tell it to, Java won’t treat it differently than any other file. The only drawback is that the filename is guaranteed to be at least 8 characters long (minimum of 3 characters for the prefix, plus 5 or more characters generated by the function).

If that’s too long for you, I suppose you could always just start with the filename «a», and loop through «b», «c», etc until you find one that doesn’t already exist.

generate files with unique names and write data into them

You could use a simple counter as a file prefix. You’d have to persist the current state of the counter between different runs of the program, though, e.g. also in the database. Here’s a question dealing with the same issue and answers containing your current approach and others.

Unique File name using system time in Java?

You can use System.currentTimeInMillis

How to create a unique file name?

public class MYValueRecorder String fileName; 
myValueRecorder () Time t= new Time();
t.setToNow();
int timeFileMinute= t.minute;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;

long timestamp=System.currentTimeMillis();

//creating file name
fileName= "MathsRaw-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;
>

public void writeToFileRawData(String data) // do your stuff here, just don't initialize fileName again.
>
>

Use this, initialize a new class at the beginning of your session, then only use the writeToFileRawData method to write your data.

How to get short-filenames in Windows using Java?

Self Answer

There are related questions with related answers. I post this solution, however, because it uses Java(tm) code without the need for external libraries. Additional solutions for different versions of Java and/or Microsoft(R) Windows(tm) are welcome.

Main Concept

Main concept lies in calling CMD from Java(tm) by means of the runtime class:

cmd /c for %I in («[long file name]») do @echo %~fsI

Solution

Tested on Java SE 7 running on Windows 7 system
(Code has been reduced for brevity).

 public static String getMSDOSName(String fileName) 
throws IOException, InterruptedException
String path = getAbsolutePath(fileName);

// changed "+ fileName.toUpperCase() +" to "path"
Process process =
Runtime.getRuntime().exec(
"cmd /c for %I in (\"" + path + "\") do @echo %~fsI");

process.waitFor();

byte[] data = new byte[65536];
int size = process.getInputStream().read(data);

if (size return null;

return new String(data, 0, size).replaceAll("\\r\\n", "");
>

public static String getAbsolutePath(String fileName)
throws IOException File file = new File(fileName);
String path = file.getAbsolutePath();

if (file.exists() == false)
file = new File(path);

path = file.getCanonicalPath();

if (file.isDirectory() && (path.endsWith(File.separator) == false))
path += File.separator;

return path;
>

Produce and resolve short file path

I want a collision free hash value

A hash is never collision free, but you can choose a hash algorith which is extremely unlikely to have collisions, as Jon Skeet explained.

How can I produce a shorter file path?

You need to distiguish two responsibilities.

  1. The hash value for the file gives you fast collision detection.
  2. Produce a short file path. Take a look at alphabet conversion theory and Java UrlShortener implementation.
Читайте также:  Php parse template file

To handle #2 you follow these steps:

  1. Save real file path in database
  2. You get a unique row ID for that
  3. Convert row ID to short string with encode()
  4. Use the short string as your short file path
  1. Decode the short file path to an integer ID with decode()
  2. Look up real file path in database for given ID

Random file name generation function takes minutes to generate unique name

There are many problems with this code:

  • SELECT , then INSERT is prone to a race condition (between the two statements another process inserted the same ID). The clean way is to optimisticly insert a row, and retry on duplicate key errors, better still use a deterministicly unique function.
  • You prepare a new statement for every loop. The clean way is to prepare the statement once, then ececute it repeatedly with the different parameters. This is why they are called prepared statements
  • Your implementation uses PHP’s rand() function, which produces wildly different qualities of randomness depending on PHP Version and OS. Use mt_rand();

I recommend you create the identifier inside the DB: See my answer to another SO question

Источник

What is the best way to generate a unique and short file name in Java

When working with files in Java, it is often necessary to generate unique and short file names. Here are the best ways to achieve this:

Using UUID

UUID (Universally Unique Identifier) is a 128-bit number used to uniquely identify information. You can generate a unique file name using UUID as shown below:

import java.util.UUID; public class UniqueFileNameGenerator < public static String generateFileNameWithUUID(String originalFileName) < String extension = originalFileName.substring(originalFileName.lastIndexOf('.')); return UUID.randomUUID().toString() + extension; >> 

Using current time in milliseconds

Another approach to generate a unique file name is to use the current time in milliseconds. This approach is not as reliable as using UUID, but it can be sufficient in some cases.

public class UniqueFileNameGenerator < public static String generateFileNameWithTime(String originalFileName) < String extension = originalFileName.substring(originalFileName.lastIndexOf('.')); long timestamp = System.currentTimeMillis(); return timestamp + extension; >> 

Using Base64 encoding

Base64 encoding is a way to encode binary data in ASCII text format. You can use Base64 encoding to generate a unique file name as shown below:

import java.util.Base64; public class UniqueFileNameGenerator < public static String generateFileNameWithBase64(String originalFileName) < String extension = originalFileName.substring(originalFileName.lastIndexOf('.')); byte[] bytes = originalFileName.getBytes(); String encoded = Base64.getEncoder().encodeToString(bytes); return encoded + extension; >> 

Conclusion

Generating unique and short file names is a common requirement in Java programming. You can use UUID, current time, or Base64 encoding to achieve this. The choice of method depends on your specific use case.

Источник

Оцените статью