Reputation: 38655
I write application in Java using SWT. I would like to create unique file name. But I do not want create it on hard drive. Additional functionality: I want to create unique file name in specify folder.
public String getUniqueFileName(String directory, String extension) {
//create unique file name
}
Upvotes: 42
Views: 57801
Reputation: 9839
Using the Path API available from Java 7 you can generate a temporary Path file with a uniquely generated name.
The Files
utility class provides Files.createTempFile
, which works in a similar manner as File.createTempFile
, except it produces a Path object
So calling the method
Path baseDir = ...
Files.createTempFile(baseDir, "status-log-", ".log");
// //dir path, prefix , suffix
Will produce something similar to
C:\...\status-log-4746781128777680321.log
If you want to open the file and delete it after you're done with it, you can use DELETE_ON_CLOSE
, taken from the docs:
As with the File.createTempFile methods, this method is only part of a temporary-file facility. Where used as a work files, the resulting file may be opened using the DELETE_ON_CLOSE option so that the file is deleted when the appropriate close method is invoked. Alternatively, a shutdown-hook, or the File.deleteOnExit mechanism may be used to delete the file automatically.
Upvotes: 4
Reputation: 301
you can create an actual unique directory (sub-directory) and then any file inside it should be unique, for example "myFile." + extension
public static String getUniqueFileName(String directory, String extension) {
try
{
// create actual unique subdirectory in the given directory
//
File myUniqueDir = File.createTempFile("udir", null,directory);
String filename = myUniqueDir.getName();
myUniqueDir.delete (); // don't want the file but a directory
myUniqueDir.mkdirs ();
}
//todo: catch ....
// for example:
return directory + "/" + myUniqueDir + "/myFile." + extension;
}
this procedure should work in normal scenarios even with concurrency. Unless we start thinking in sniffer processes that want to occupy our new directory or similar things.
Upvotes: 2
Reputation: 34207
Simplified the other answers, Use GUID. imho no need to add salt to UUID
. This is what i'm using:
public static String getUniqueFileName(String directory, String extension) {
String fileName = MessageFormat.format("{0}.{1}", UUID.randomUUID(), extension.trim());
return Paths.get(directory, fileName).toString();
}
usage:
String uniqueFileName = getUniqueFileName("/tmp", "pdf");
System.out.println(uniqueFileName);
output
/tmp/f34a960a-6001-44d6-9aa7-93ec6647a64a.pdf
Upvotes: 3
Reputation: 193696
From your question I assume you've seen that File.createTempFile()
always creates a file rather than just allowing you to generate the name.
But why not just call the method and then delete the temporary file created? createTempFile()
does all the work in finding a unique file name in the specified directory and since you created the file you can sure you'll be to delete it too.
File f = File.createTempFile("prefix",null,myDir);
String filename = f.getName();
f.delete();
Upvotes: 24
Reputation: 84038
Use a timestamp in the filename?
Of course this may not work if you have very high concurrency.
For example:
public String getUniqueFileName(String directory, String extension) {
return new File(directory, new StringBuilder().append("prefix")
.append(date.getTime()).append(UUID.randomUUID())
.append(".").append(extension).toString()).getAbsolutePath();
}
AS John Oxley's answer suggests. UUID may be a solution as you can use 4 different schemes to create them. Though there is still a small chance of a collision. If you combine a timestamp with a random UUID the chances of any collision becomes vanishingly small.
Upvotes: 7
Reputation: 1340
You can create a file with any name (time, GUID, etc) and then test it to see if it already exists. If it does, then try another name to see if it's unique.
File f = new File(guid);
if (f.exists()) {
//try another guid
}else{
//you're good to go
}
Upvotes: 1
Reputation: 14990
Use a GUID
Upvotes: 30