首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Java中创建临时目录/文件夹?

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

Stack Overflow用户
提问于 2009-03-06 01:17:55
回答 13查看 436.1K关注 0票数 403

有没有一种在Java应用程序中创建临时目录的标准且可靠的方法?有一个an entry in Java's issue database,它的注释中有一些代码,但我想知道在一个常用的库(Apache Commons等)中是否有标准的解决方案?

EN

回答 13

Stack Overflow用户

回答已采纳

发布于 2009-03-06 01:31:28

如果您使用的是JDK7,请使用新的Files.createTempDirectory类来创建临时目录。

代码语言:javascript
复制
Path tempDirWithPrefix = Files.createTempDirectory(prefix);

在JDK 7之前,应该这样做:

代码语言:javascript
复制
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)。

票数 425
EN

Stack Overflow用户

发布于 2011-06-20 01:15:17

Google Guava库有大量有用的实用程序。这里值得注意的一点是Files class。它有很多有用的方法,包括:

代码语言:javascript
复制
File myTempDir = Files.createTempDir();

这在一行代码中恰好满足了您的要求。如果您阅读了文档,dir`通常会引入安全漏洞。

票数 183
EN

Stack Overflow用户

发布于 2012-01-25 14:58:53

这是Guava库的Files.createTempDir()的源代码。它并不像你想象的那么复杂:

代码语言:javascript
复制
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) + ')');
}

默认情况下:

代码语言:javascript
复制
private static final int TEMP_DIR_ATTEMPTS = 10000;

See here

票数 38
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/617414

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档