是否存在在Java应用程序中创建临时目录的标准可靠方法?Java的问题数据库中有一个条目,注释中包含一些代码,但是我想知道是否可以在一种常用的库(Apache Commons等)中找到一种标准解决方案?
如果您使用的是JDK 7,请使用新的Files.createTempDirectory类创建临时目录。
Path tempDirWithPrefix = Files.createTempDirectory(prefix);
在JDK 7之前,应该这样做:
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子类)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句