如何在Java中创建临时目录/文件夹?

是否有标准且可靠的方法可以在 Java 应用程序中创建临时目录?Java的问题数据库中有一个条目,它在注释中有一些代码,但我想知道是否有一个标准的解决方案可以在一个常用的库(Apache Commons等)中找到?


答案 1

如果您使用的是 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)。


答案 2

谷歌番石榴库有大量有用的实用程序。这里需要注意的一点是 Files 类。它有一堆有用的方法,包括:

File myTempDir = Files.createTempDir();

这完全符合您在一行中的要求。如果您阅读此处的文档,您将看到建议的改编通常会引入安全漏洞。File.createTempFile("install", "dir")