开发者

Unique File name using system time in Java?

I want to use unique id for the files. How can I use system time to generate unique IDs in Java?开发者_StackOverflow


You're looking for the UUID class.


UUID class is what you need.

Sample implementation :

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

Output :

Random UUID String = 7dc53df5-703e-49b3-8670-b1c468f47f1f
UUID version       = 4
UUID variant       = 2


I'd recommend using File.createTempFile(String prefix, String suffix) which creates an empty file that doesn't collide with anything else on the file system.

You can use File.deleteOnExit to ensure that it's deleted when the program exits.


You can use System.currentTimeInMillis

or

java.util.UUID.randomUUID()


Does it have to be based on the system time? Can't you just use a UUID?

java.util.UUID.randomUUID();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜