File.delete() 直接删除文件
File.deleteOnExit() 在退出时删除:
public void deleteOnExit() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkDelete(path);
}
if (isInvalid()) {
return;
}
DeleteOnExitHook.add(path);
}
最终把path添加到DeleteOnExitHook中
/**
* This class holds a set of filenames to be deleted on VM exit through a shutdown hook.
* A set is used both to prevent double-insertion of the same file as well as offer
* quick removal.
*/
//解释:VM(虚拟机) 退出时才删除文件。
class DeleteOnExitHook {
private static LinkedHashSet<String> files = new LinkedHashSet<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
runHooks();
}
});
}
private DeleteOnExitHook() {}
static synchronized void add(String file) {
if(files == null) {
throw new IllegalStateException("Shutdown in progress");
}
files.add(file);
}
//虚拟机退出时会调用runHooks函数,利用LinkedHashSet 存储的路径删除文件
static void runHooks() {
LinkedHashSet<String> theFiles;
synchronized (DeleteOnExitHook.class) {
theFiles = files;
files = null;
}
ArrayList<String> toBeDeleted = new ArrayList<>(theFiles);
// reverse the list to maintain previous jdk deletion order.
// Last in first deleted.
Collections.reverse(toBeDeleted);
for (String filename : toBeDeleted) {
(new File(filename)).delete();
}
}
}