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(); } }