gpt4 book ai didi

java - 删除临时目录

转载 作者:行者123 更新时间:2023-11-29 03:58:21 25 4
gpt4 key购买 nike

我在这里找到了一些用 Java 创建临时目录的代码。

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;
}

我怎样才能在我的 servlet 生命结束时处理这个临时目录并将其删除?

最佳答案

首先:

不要使用这种创建临时目录的方法! 这是不安全的!使用Guava方法 Files.createTempDir() 相反(或者手动重新实现它,如果你不想使用 Guava )。其JavaDoc中描述了原因:

A common pitfall is to call createTempFile, delete the file and create a directory in its place, but this leads a race condition which can be exploited to create security vulnerabilities, especially when executable files are to be written into the directory.

关于你真正的问题:

您需要手动删除目录,这意味着您需要跟踪您创建的所有目录(例如在 Collection<File> 中)并在您确定不再需要它们时删除它们。

关于java - 删除临时目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5039816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com