这篇文章主要介绍了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 }
效果图:
点击创建临时文件效果图:
非常简单实用的功能,希望小伙伴们能够喜欢。