我在一个非常大的应用程序中使用Java
,有时我必须使用临时文件。我想在应用程序关闭时删除那些文件,这是我正在使用的简单快照:
File tempFile = File.createTempFile("sign_", "tmp.pdf");
tempFile.deleteOnExit();
我不会报告所有代码,因为它真的很大,而且我有很多类互相工作。我想知道这可能是避免在关闭某些文件时删除的原因(某些文件被删除,另一些则未被删除,但它们始终来自与未删除的同一代码段)。
编辑:我已经读过 this example但我认为我需要一些“理论”动机而不是代码示例来找到原因。
最佳答案
“deleteOnExit()”方法仅在虚拟机正常终止时才有效。如果虚拟机崩溃或强制终止,文件可能不会被删除。
我不知道它是如何实现的,但你可以尝试将 tempFile.deleteOnExit() 放在finally中。
File tempFile = null;
try{
tempFile = File.createTempFile("sign_", "tmp.pdf");
}catch(IOException e){
e.printStackTrace();
} finally {
if (tempFile != null) {
tempFile.deleteOnExit();
tempFile = null;
//Added a call to suggest the Garbage Collector
//To collect the reference and remove
System.gc();
}
}
或者,关闭对文件的所有引用,然后调用“File.delete()”立即删除。
如果有人在工作,可能存在对该文件的一些引用。通过这种方式,您可以尝试使用org.apache.commons.io.FileUtils强制删除文件。
示例org.apache.commons.io.FileUtils:
File tempFile = null;
try{
tempFile = File.createTempFile("sign_", "tmp.pdf");
}catch(IOException e){
e.printStackTrace();
} finally {
if (tempFile != null) {
FileUtils.forceDelete(tempFile);
System.out.println("File deleted");
}
}
示例org.apache.commons.io.FileDeleteStrategy:
File tempFile = null;
try{
tempFile = File.createTempFile("sign_", "tmp.pdf");
}catch(IOException e){
e.printStackTrace();
} finally {
if (tempFile != null) {
FileDeleteStrategy.FORCE.delete(tempFile);
System.out.println("File deleted");
}
}
关于java - 关闭时未删除临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35579817/