是否有一种标准且可靠的方法在 Java 应用程序中创建临时目录?有Java 问题数据库中的一个条目 http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4735419,其中的注释中有一些代码,但我想知道是否可以在常用的库之一(Apache Commons 等)中找到标准解决方案?
如果您使用的是 JDK 7,请使用新的文件.createTempDirectory http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempDirectory%28java.nio.file.Path,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...%29类来创建临时目录。
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 子类)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)