tags:

views:

1724

answers:

5

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 
}
+2  A: 

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());
}

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.

Rich Seller
+3  A: 

You could try using a GUID for the file name.

JonnyD
+1  A: 

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
}
Nick
@Nick: between `f.exists()` and `//you're good to go` a file with that name could appear on the file system.
Grant Wagner
A: 

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();
Dave Webb
@Dave: After `f.delete()` the file name is no longer guaranteed to be unique. Right after you remove the one created by `createTempFile()` another file with the same name could appear on the file system.
Grant Wagner