這篇文章主要介紹了java實現創建臨時文件然后在程序退出時自動刪除文件,從個人項目中提取出來的,小伙伴們可以直接拿走使用。
通過java的File類創建臨時文件,然后在程序退出時自動刪除臨時文件。下面將通過創建一個JFrame界面,點擊創建按鈕在當前目錄下面創建temp文件夾且創建一個以mytempfile******.tmp格式的文本文件。代碼如下:
1 import java.io.*; 2 import java.util.*; 3 import javax.swing.*; 4 import java.awt.event.*; 5 6 /** 7 * 功能: 創建臨時文件(在指定的路徑下) 8 */ 9 public class TempFile implements ActionListener { 10 11 private File tempPath; 12 13 public static void main(String args[]){ 14 TempFile ttf = new TempFile(); 15 ttf.init(); 16 ttf.createUI(); 17 } 18 19 //創建UI 20 public void createUI() { 21 JFrame frame = new JFrame(); 22 JButton jb = new JButton("創建臨時文件"); 23 jb.addActionListener(this); 24 frame.add(jb,"North"); 25 frame.setSize(200,100); 26 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 27 frame.setVisible(true); 28 } 29 30 //初始化 31 public void init(){ 32 tempPath = new File("./temp"); 33 if(!tempPath.exists() || !tempPath.isDirectory()) { 34 tempPath.mkdir(); //如果不存在,則創建該文件夾 35 } 36 } 37 38 //處理事件 39 public void actionPerformed(ActionEvent e) { 40 try { 41 //在tempPath路徑下創建臨時文件"mytempfileXXXX.tmp" 42 //XXXX 是系統自動產生的隨機數, tempPath對應的路徑應事先存在 43 File tempFile = File.createTempFile("mytempfile", ".txt", tempPath); 44 System.out.println(tempFile.getAbsolutePath()); 45 FileWriter fout = new FileWriter(tempFile); 46 PrintWriter out = new PrintWriter(fout); 47 out.println("some info!" ); 48 out.close(); //注意:如無此關閉語句,文件將不能刪除 49 //tempFile.delete(); 50 tempFile.deleteOnExit(); 51 } catch(IOException e1) { 52 System.out.println(e1); 53 } 54 } 55 56 }
效果圖:
點擊創建臨時文件效果圖:
非常簡單實用的功能,希望小伙伴們能夠喜歡。