我不一定要使用UUID,因为它们相当长。
该文件只需要在其目录中是唯一的。
脑海中浮现的一个想法是使用File.createTempFile(String prefix, String suffix)
,但这似乎是错误的,因为文件不是临时的。
需要处理在同一毫秒内创建两个文件的情况。
发布于 2009-05-05 16:22:01
嗯,你可以使用3参数版本:File.createTempFile(String prefix, String suffix, File directory)
,它可以让你把它放在你想放的地方。除非您告诉它,否则Java不会将它与任何其他文件区别对待。唯一的缺点是保证文件名的长度至少为8个字符(最少3个字符作为前缀,加上由函数生成的5个或更多字符)。
如果这对你来说太长了,我想你总是可以从文件名"a“开始,然后遍历"b","c",等等,直到你找到一个不存在的文件名。
发布于 2013-09-04 14:24:18
这对我来说很有效:
String generateUniqueFileName() {
String filename = "";
long millis = System.currentTimeMillis();
String datetime = new Date().toGMTString();
datetime = datetime.replace(" ", "");
datetime = datetime.replace(":", "");
String rndchars = RandomStringUtils.randomAlphanumeric(16);
filename = rndchars + "_" + datetime + "_" + millis;
return filename;
}
// USE:
String newFile;
do{
newFile=generateUniqueFileName() + "." + FileExt;
}
while(new File(basePath+newFile).exists());
输出文件名应如下所示:
2OoBwH8OwYGKW2QE_4Sep2013061732GMT_1378275452253.Ext
发布于 2009-05-05 16:31:12
看看File javadoc,createNewFile方法将仅在文件不存在时创建该文件,并将返回一个布尔值来说明该文件是否已创建。
您还可以使用exists()方法:
int i = 0;
String filename = Integer.toString(i);
File f = new File(filename);
while (f.exists()) {
i++;
filename = Integer.toString(i);
f = new File(filename);
}
f.createNewFile();
System.out.println("File in use: " + f);
https://stackoverflow.com/questions/825678
复制相似问题