使用Shutdown-Hook删除临时文件
import java.io.IOException; /*来自 时 代 Java 公 众 号 - nowjava.com*/ import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; public class Main { public static void main(String[] args) throws Exception { Path basedir = FileSystems.getDefault().getPath("C:/folder1/tmp"); String tmp_file_prefix = "test_"; String tmp_file_sufix = ".txt"; Path tmp_file = Files.createTempFile(basedir, tmp_file_prefix,/*时代Java公众号 - nowjava.com 提供*/ tmp_file_sufix); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("Deleting the temporary file ..."); try { Files.delete(tmp_file); }