java实现建立临时文件而后在程序退出时自动删除文件(转)

  这篇文章主要介绍了java实现建立临时文件而后在程序退出时自动删除文件,从我的项目中提取出来的,小伙伴们能够直接拿走使用。java

  经过java的File类建立临时文件,而后在程序退出时自动删除临时文件。下面将经过建立一个JFrame界面,点击建立按钮在当前目录下面建立temp文件夹且建立一个以mytempfile******.tmp格式的文本文件。代码以下:this

 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 }

效果图:spa

点击建立临时文件效果图:code

 

  很是简单实用的功能,但愿小伙伴们可以喜欢。orm

相关文章
相关标签/搜索