使用DELETE_ON_CLOSE删除临时文件
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; /** from * nowjava.com - 时代Java **/ import java.io.OutputStreamWriter; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; 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 = null; try { tmp_file = Files.createTempFile(basedir, tmp_file_prefix, tmp_file_sufix); } catch (IOException e) { System.err.println(e); /** from * NowJava.com **/ } try (OutputStream outputStream = Files.newOutputStream(tmp_file, StandardOpenOption.DELETE_ON_CLOSE); BufferedWriter writer =