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

这篇博客讨论了在Java应用程序中创建临时目录的可靠方法,包括避免使用`deleteOnExit()`的原因,并推荐使用Apache Commons IO的`FileUtils`。文章还提醒读者理解临时目录的生命周期,并提供了不同技术领域的学习资源。
摘要由CSDN通过智能技术生成

个人博客导航页(点击右侧链接即可打开个人博客):大牛带你入门技术栈 

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


#1楼

这是我决定为自己的代码执行的操作:

/**
 * Create a new temporary directory. Use something like
 * {@link #recursiveDelete(File)} to clean this directory up since it isn't
 * deleted automatically
 * @return  the new directory
 * @throws IOException if there is an error creating the temporary directory
 */
public static File createTempDir() throws IOException
{
    final File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
    File newTempDir;
    final int maxAttempts = 9;
    int attemptCount = 0;
    do
    {
        attemptCount++;
        if(attemptCount > maxAttempts)
        {
            throw new IOException(
                    "The highly improbable has occurred! Failed to " +
                    "create a unique temporary directory after " +
                    maxAttempts + " attempts.");
        }
        String dirName = UUID.randomUUID().toString();
        newTempDir = new File(sysTempDir, dirName);
    } w
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值