有没有一种在Java应用程序中创建临时目录的标准且可靠的方法?有一个an entry in Java's issue database,它的注释中有一些代码,但我想知道在一个常用的库(Apache Commons等)中是否有标准的解决方案?
发布于 2009-03-06 01:31:28
如果您使用的是JDK7,请使用新的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)。
发布于 2011-06-20 01:15:17
Google Guava库有大量有用的实用程序。这里值得注意的一点是Files class。它有很多有用的方法,包括:
File myTempDir = Files.createTempDir();
这在一行代码中恰好满足了您的要求。如果您阅读了文档,dir`通常会引入安全漏洞。
发布于 2012-01-25 14:58:53
这是Guava库的Files.createTempDir()的源代码。它并不像你想象的那么复杂:
public static File createTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
String baseName = System.currentTimeMillis() + "-";
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException("Failed to create directory within "
+ TEMP_DIR_ATTEMPTS + " attempts (tried "
+ baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
}
默认情况下:
private static final int TEMP_DIR_ATTEMPTS = 10000;
https://stackoverflow.com/questions/617414
复制相似问题