删除临时目录
我在这里找到了一些用于在 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 生命周期结束时,如何处理这个临时目录并将其删除?
I found some code on here for creating temporary directories in 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;
}
How can I at the end of my servlet's life a handle on this temporary directory and delete it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一:
不要使用这种创建临时目录的方法! 这是不安全的!使用Guava方法
Files.createTempDir()
相反(或者如果您不想使用 Guava,则手动重新实现)。其JavaDoc中描述了原因:关于您真正的问题:
您需要手动删除目录,这意味着您需要跟踪您创建的所有目录(例如在
Collection
中),并在确定时删除它们不再需要它们。First:
Don't use this method of creating a temporary directory! It is unsafe! Use the Guava method
Files.createTempDir()
instead (or re-implement it manually, if you don't want to use Guava). The reason is described in its JavaDoc:Regarding your real question:
You need to delete the directory manually, which means you need to keep track of all directories you create (for example in a
Collection<File>
) and delete them when you know for sure that they are not longer needed.