如果我为某些写入操作创建临时文件,是否有任何方法可以在程序中指定在程序终止时自动删除它。
以下是创建文件的过程。
File tmp = File.createTempFile("foo", "tmp");
System.out.println("Your temp file is " + tmp.getCanonicalPath());
//doing something with the temporary file
writeDataInTemp(tmp.getCanonicalPath());
最佳答案
使用关闭 Hook 并自行完成: https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)
(库和框架可能就是这样做的。它允许您定义一个在 JVM 终止时运行的函数)
您想要在某个地方建立所有临时文件的列表(我建议您使用一些不错的 getTemporaryFile() 函数,它可以获取文件句柄并将名称添加到要删除的内容列表中),然后在你的关闭钩子(Hook)中杀死它们。
关于java - 程序终止时临时文件删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35809727/