目的:测试强行停止程序时deleteOnExit()能否生效。
测试代码如下:
import java.io.*;
public class DeltetOnExit {
public static void main(String[] args) {
//分别调用t1、t2、t3方法进行试验
}
public static void t1(){//没有deleteOnExit,程序抛异常停止,结果文件保留(未被删除)
File f=new File("e:"+File.separator+"java"+File.separator+"javarun","delete_on_exit_demo1");
try{
f.createNewFile();
throw new RuntimeException();
}
catch(IOException e){
}
}
public static void t2(){//有deleteOnExit,程序抛异常停止,结果文件未保留(被删除)
File f=new File("e:"+File.separator+"java"+File.separator+"javarun","delete_on_exit_demo2");
try{
f.createNewFile();
f.deleteOnExit();
throw new RuntimeException();
}
catch(IOException e){
}
}
public static void t3(){//有deleteOnExit,程序死循环,强行停止(Ctrl+C等方法),结果文件保留(未被删除)
File f=new File("e:"+File.separator+"java"+File.separator+"javarun","delete_on_exit_demo3");
try{
f.createNewFile();
f.deleteOnExit();
for(;;){}
}
catch(IOException e){
}
}
}
测试结果如注释所示,强行停止jvm无法删除文件。