如何在Java中创建临时目录/文件夹? [英] How to create a temporary directory/folder in Java?
问题描述
在Java应用程序中创建临时目录是否有标准可靠的方式?有 Java问题数据库中的条目,其中有一些代码意见,但我想知道是否有一个标准的解决方案可以在一个常见的库(Apache Commons等)中找到?
如果您使用的是JDK 7,请使用新的 Files.createTempDirectory 类创建临时目录。 p>
在JDK 7之前,应该这样做:
public static File createTempDirectory )
throws IOException
{
final File temp;
temp = File.createTempFile(temp,Long.toString(System.nanoTime()));
如果(!(temp.delete()))
{
抛出新的IOException(无法删除临时文件:+ temp.getAbsolutePath());
}
if(!(temp.mkdir()))
{
抛出新的IOException(无法创建临时目录:+ temp.getAbsolutePath ));
}
return(temp);
}
如果需要,您可以制作更好的异常(子类IOException)。
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.) ?
If you are using JDK 7 use the new Files.createTempDirectory class to create the temporary directory.
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);
}
You could make better exceptions (subclass IOException) if you want.
这篇关于如何在Java中创建临时目录/文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!