delete() 是即刻删除
public boolean delete() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkDelete(path); } if (isInvalid()) { return false; } return fs.delete(this); } 最终调用native本地方法 立即进行删除
deleteOnExit() 调用后,不会立即删除,会等到虚拟机正常运行结束后,才去删除
public void deleteOnExit() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkDelete(path); } if (isInvalid()) { return; } DeleteOnExitHook.add(path); }
private DeleteOnExitHook() {} static synchronized void add(String file) { if(files == null) { // DeleteOnExitHook is running. Too late to add a file throw new IllegalStateException("Shutdown in progress"); } files.add(file); } 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(); } }