2016-02-23 52 views
0

我在一个非常大的应用程序中使用了Java,并且有时候我必须使用临时文件。这些文件我想在应用程序关闭时被删除,这是一个简单的快照,我使用:临时文件在关闭时未被删除

File tempFile = File.createTempFile("sign_", "tmp.pdf"); 
tempFile.deleteOnExit(); 

我不报告所有的代码,因为是非常大的,我有很多工作类彼此。我会知道哪些可能是避免关闭某些文件时删除的原因(某些文件被删除了其他文件,但它们始终来自同一段不被删除的文件)。

编辑:我已经阅读this example但我想我需要一些“理论”的动机,而不是代码示例来找到原因。

+1

[“删除将仅尝试用于正常终止虚拟机,如Java Language Specification所定义。“](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#deleteOnExit())是JVM退出异常? –

+3

如果这是你的真实代码,你不需要设置tmp.deleteOnExit();到tempFile.deleteOnExit()? – Alex

+0

@AlexClem我从另一段代码复制而来,你是对的!我在编辑 – Razlo3p

回答

1

方法“deleteOnExit()”只适用于VM正常终止。如果虚拟机崩溃或强制终止,该文件可能会保持未删除状态。

我不知道它是如何实现的,但你可以尝试把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()”来立即删除。

如果有人正在工作,可能存在对文件的某些引用。这样,你可以尝试force使用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"); 
    } 
} 
+0

试过但没有,文件仍然存在 – Razlo3p

+0

我更新了答案,包括在设置tempFile = null之后调用垃圾收集器尝试收集参考。此外,还包括两种不同的方式来强制删除 – Brother

+0

这种方法,我仍然有一个例外: 无法删除文件:C:\ Users \ USERNAME \ AppData \ Local \ Temp \ tmp.pdf – Razlo3p