File.createTempFile(prefix, suffix, directory):在指定目錄創建唯一臨時文件,文件名格式 prefix+隨機數+suffix。file.deleteOnExit():註冊 JVM 關閉鉤子,虛擬機正常退出時自動刪除該文件。
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class TempFileDemo implements ActionListener {
private File tempDir;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TempFileDemo().initUI());
}
private void initUI() {
tempDir = new File("./temp");
if (!tempDir.exists()) tempDir.mkdirs();
JFrame frame = new JFrame("臨時文件演示");
JButton btn = new JButton("創建臨時文件");
btn.addActionListener(this);
frame.add(btn, "North");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
// 創建臨時文件:前綴 mytempfile,後綴 .txt,目錄 tempDir
File tempFile = File.createTempFile("mytempfile", ".txt", tempDir);
System.out.println("文件路徑: " + tempFile.getAbsolutePath());
// 寫入測試數據
try (PrintWriter out = new PrintWriter(new FileWriter(tempFile))) {
out.println("臨時文件測試內容 - " + System.currentTimeMillis());
}
// 關鍵:註冊 JVM 退出自動刪除
tempFile.deleteOnExit();
JOptionPane.showMessageDialog(null, "臨時文件已創建,程序退出時將自動刪除。");
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "創建失敗: " + ex.getMessage());
}
}
}
createTempFile 要求目標目錄必須存在,否則拋 IOException。close() 流(示例用 try-with-resources),否則 Windows 下文件被佔用導致 deleteOnExit 失敗。Runtime.addShutdownHook,僅在正常退出(System.exit、主線程結束)生效;kill -9、崩潰、掉電不生效。| 方案 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
deleteOnExit() | 短生命周期緩存、測試數據 | 代碼極簡、無需手動清理 | 佔用內存註冊表、異常退出不刪除、大量文件影響啟動速度 |
| ShutdownHook 手動清理目錄 | 批量臨時文件、目錄級清理 | 可控性強、可清理子目錄 | 代碼稍多 |
| 定時任務掃描清理 | 長運行服務、異常退出補救 | 覆蓋面廣 | 需額外調度、延遲刪除 |
| try-with-resources + 手動 delete | 明確生命周期、即用即刪 | 即時釋放、無殘留風險 | 需開發者嚴格管理 |
System.getProperty("java.io.tmpdir")),避免硬編碼相對路徑。order_export_),便於日誌排查。try-with-resources 手動刪除,輔以定時掃描任務作為安全網。File.createTempFile + deleteOnExit() 是 Java 處理短壽命臨時文件的標準組合拳。理解其機制邊界(正常退出、流關閉、目錄存在),並根據業務壽命選擇合適清理策略,是穩健文件處理的關鍵。