在 Java 中使用系统时间的唯一文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6064022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unique File name using system time in Java?
提问by leon
I want to use unique id for the files. How can I use system time to generate unique IDs in Java?
我想对文件使用唯一的 id。如何使用系统时间在 Java 中生成唯一 ID?
采纳答案by Basanth Roy
You can use System.currentTimeInMillis
您可以使用 System.currentTimeInMillis
or
或者
java.util.UUID.randomUUID()
java.util.UUID.randomUUID()
回答by sgokhales
UUID classis what you need.
UUID 类正是您所需要的。
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
回答by aioobe
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.
我建议使用File.createTempFile(String prefix, String suffix)
which 创建一个空文件,该文件不会与文件系统上的任何其他内容发生冲突。
You can use File.deleteOnExit
to ensure that it's deleted when the program exits.
您可以使用File.deleteOnExit
来确保它在程序退出时被删除。
回答by alpian
Does it have to be based on the system time? Can't you just use a UUID?
是否必须基于系统时间?你不能只使用 UUID 吗?
java.util.UUID.randomUUID();