如何在 Java 中创建临时目录/文件夹? [英] How to create a temporary directory/folder in Java?
问题描述
在 Java 应用程序中是否有一种标准且可靠的方法来创建临时目录?有 Java 问题数据库中的一个条目,其中有一些代码评论,但我想知道是否可以在常用库之一(Apache Commons 等)中找到标准解决方案?
Is there a standard and reliable way of creating a temporary directory inside a Java application? There's an entry in Java's issue database, which has a bit of code in the comments, but I wonder if there is a standard solution to be found in one of the usual libraries (Apache Commons etc.) ?
推荐答案
如果您使用的是 JDK 7,请使用新的 文件.createTempDirectory 类来创建临时目录.
If you are using JDK 7 use the new Files.createTempDirectory class to create the temporary directory.
Path tempDirWithPrefix = Files.createTempDirectory(prefix);
在 JDK 7 之前应该这样做:
Before JDK 7 this should do it:
public static File createTempDirectory()
throws IOException
{
final File temp;
temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
if(!(temp.delete()))
{
throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
}
if(!(temp.mkdir()))
{
throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
}
return (temp);
}
如果需要,您可以创建更好的异常(IOException 子类).
You could make better exceptions (subclass IOException) if you want.
这篇关于如何在 Java 中创建临时目录/文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!