Java 如何在不创建文件的情况下创建 tmp 文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1293655/
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
How to create tmp file name with out creating file
提问by Micha? Ziober
I write application in Java using SWT. I would like to create unique file name. But I do not want create it on hard drive. Additional functionality: I want to create unique file name in specify folder.
我使用 SWT 用 Java 编写应用程序。我想创建唯一的文件名。但我不想在硬盘上创建它。附加功能:我想在指定文件夹中创建唯一的文件名。
public String getUniqueFileName(String directory, String extension) {
//create unique file name
}
采纳答案by John Oxley
回答by Rich Seller
Use a timestamp in the filename?
在文件名中使用时间戳?
Of course this may not work if you have very high concurrency.
当然,如果您的并发性非常高,这可能不起作用。
For example:
例如:
public String getUniqueFileName(String directory, String extension) {
return new File(directory, new StringBuilder().append("prefix")
.append(date.getTime()).append(UUID.randomUUID())
.append(".").append(extension).toString()).getAbsolutePath();
}
AS John Oxley's answer suggests. UUIDmay be a solution as you can use 4 different schemes to create them. Though there is still a small chance of a collision. If you combine a timestamp with a random UUID the chances of any collision becomes vanishingly small.
正如约翰奥克斯利的回答所暗示的那样。UUID可能是一种解决方案,因为您可以使用 4 种不同的方案来创建它们。虽然碰撞的可能性仍然很小。如果将时间戳与随机 UUID 结合使用,则任何碰撞的机会都会变得非常小。
回答by Nick
You can create a file with any name (time, GUID, etc) and then test it to see if it already exists. If it does, then try another name to see if it's unique.
您可以创建一个具有任何名称(时间、GUID 等)的文件,然后对其进行测试以查看它是否已经存在。如果是,则尝试另一个名称以查看它是否唯一。
File f = new File(guid);
if (f.exists()) {
//try another guid
}else{
//you're good to go
}
回答by Dave Webb
From your question I assume you've seen that File.createTempFile()
always creates a file rather than just allowing you to generate the name.
从您的问题中,我假设您已经看到,它File.createTempFile()
总是会创建一个文件,而不仅仅是允许您生成名称。
But why not just call the method and then delete the temporary file created? createTempFile()
does all the work in finding a unique file name in the specified directory and since you created the file you can sure you'll be to delete it too.
但是为什么不直接调用该方法然后删除创建的临时文件呢? createTempFile()
完成在指定目录中查找唯一文件名的所有工作,并且由于您创建了该文件,因此您可以确定您也将删除它。
File f = File.createTempFile("prefix",null,myDir);
String filename = f.getName();
f.delete();
回答by Jossef Harush
Another Version,
另一个版本,
Simplified the other answers, Use GUID. imho no need to add saltto UUID
. This is what i'm using:
简化其他答案,使用 GUID。恕我直言,无需添加盐来UUID
。这就是我正在使用的:
public static String getUniqueFileName(String directory, String extension) {
String fileName = MessageFormat.format("{0}.{1}", UUID.randomUUID(), extension.trim());
return Paths.get(directory, fileName).toString();
}
- note that the file is not being created, this function just returns a unique filename as string
- 请注意,文件没有被创建,这个函数只是返回一个唯一的文件名作为字符串
usage:
用法:
String uniqueFileName = getUniqueFileName("/tmp", "pdf");
System.out.println(uniqueFileName);
output
输出
/tmp/f34a960a-6001-44d6-9aa7-93ec6647a64a.pdf
回答by elxala
you can create an actual unique directory (sub-directory) and then any file inside it should be unique, for example "myFile." + extension
您可以创建一个实际唯一的目录(子目录),然后其中的任何文件都应该是唯一的,例如“myFile”。+ 扩展
public static String getUniqueFileName(String directory, String extension) {
try
{
// create actual unique subdirectory in the given directory
//
File myUniqueDir = File.createTempFile("udir", null,directory);
String filename = myUniqueDir.getName();
myUniqueDir.delete (); // don't want the file but a directory
myUniqueDir.mkdirs ();
}
//todo: catch ....
// for example:
return directory + "/" + myUniqueDir + "/myFile." + extension;
}
this procedure should work in normal scenarios even with concurrency. Unless we start thinking in sniffer processes that want to occupy our new directory or similar things.
即使有并发,这个过程也应该在正常情况下工作。除非我们开始考虑想要占用我们的新目录或类似内容的嗅探器进程。
回答by svarog
Using the Path API available from Java 7you can generate a temporary Path file with a uniquely generated name.
使用Java 7 提供的Path API,您可以生成一个具有唯一生成名称的临时 Path 文件。
The Files
utility class provides Files.createTempFile
, which works in a similar manner as File.createTempFile
, except it produces a Path object
的Files
工具类提供Files.createTempFile
,其以类似的方式工作为File.createTempFile
,除了它产生一个路径对象
So calling the method
所以调用方法
Path baseDir = ...
Files.createTempFile(baseDir, "status-log-", ".log");
// //dir path, prefix , suffix
Will produce something similar to
会产生类似的东西
C:\...\status-log-4746781128777680321.log
If you want to open the file and delete it after you're done with it, you can use DELETE_ON_CLOSE
, taken from the docs:
如果您想打开文件并在完成后将其删除,您可以使用DELETE_ON_CLOSE
,取自文档:
As with the File.createTempFile methods, this method is only part of a temporary-file facility. Where used as a work files, the resulting file may be opened using the DELETE_ON_CLOSE option so that the file is deleted when the appropriate close method is invoked. Alternatively, a shutdown-hook, or the File.deleteOnExit mechanism may be used to delete the file automatically.
与 File.createTempFile 方法一样,此方法只是临时文件工具的一部分。在用作工作文件的情况下,可以使用 DELETE_ON_CLOSE 选项打开生成的文件,以便在调用适当的关闭方法时删除该文件。或者,可以使用关闭挂钩或 File.deleteOnExit 机制自动删除文件。