假设我用 Java 方法创建了一个临时文件
Suppose I create a temporary file in Java with the method
File tmp = File.createTempFile(prefix, suffix);
如果我没有显式调用 delete()
方法,文件什么时候会被删除?
If I do not explicity call the delete()
method, when will the file be deleted?
作为一种直觉,它可能是在 JVM 终止时,或 较早(由垃圾收集器)或 较晚(由某些操作系统清理进程).
As an intuition, it might be when the JVM terminates, or earlier (by the Garbage Collector), or later (by some Operating System sweeping process).
文件不会被自动删除,从 JavaDoc:
The file won't be deleted automatically, from the JavaDoc:
此方法仅提供临时文件功能的一部分.到安排自动删除由此方法创建的文件,使用 deleteOnExit() 方法.
This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.
所以你必须明确调用 deleteOnExit():
So you have to explicitly call deleteOnExit():
请求此抽象路径名表示的文件或目录虚拟机终止时被删除.
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
这篇关于什么时候删除 Java 临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!