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

By | August 4, 2019


I don’t necessarily want to use UUIDs since they are fairly long.

The file just needs to be unique within its directory.

One thought which comes to mind is to use File.createTempFile(String prefix, String suffix), but that seems wrong because the file is not temporary.

The case of two files created in the same millisecond needs to be handled.


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.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *