您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

java 2022/1/1 18:24:53 有338人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶