简体   繁体   中英

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?

你正在寻找UUID课程

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

You can use System.currentTimeInMillis

or

java.util.UUID.randomUUID()

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.

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

java.util.UUID.randomUUID();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM