Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file

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.

like image 414
Jeff Bloom Avatar asked May 05 '09 16:05

Jeff Bloom


People also ask

How to create unique names in Java?

To have unique name you can use hashset type of collection instead of list. For reading the data you can use scanner. readLine is a java method that takes a string prompt as a parameter.

What do you understand by file name?

A filename or file name is a name used to uniquely identify a computer file in a directory structure.


1 Answers

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.

like image 72
Pesto Avatar answered Sep 20 '22 23:09

Pesto