通過java的File類創(chuàng)建臨時文件,然后在程序退出時自動刪除臨時文件。下面將通過創(chuàng)建一個JFrame界面,點擊創(chuàng)建按鈕在當前目錄下面創(chuàng)建temp文件夾且創(chuàng)建一個以mytempfile******.tmp格式的文本文件。代碼如下:
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
/**
* 功能: 創(chuàng)建臨時文件(在指定的路徑下)
*/
public class TempFile implements ActionListener
{
private File tempPath;
public static void main(String args[]){
TempFile ttf = new TempFile();
ttf.init();
ttf.createUI();
}
//創(chuàng)建UI
public void createUI()
{
JFrame frame = new JFrame();
JButton jb = new JButton("創(chuàng)建臨時文件");
jb.addActionListener(this);
frame.add(jb,"North");
frame.setSize(200,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//初始化
public void init(){
tempPath = new File("./temp");
if(!tempPath.exists() || !tempPath.isDirectory())
{
tempPath.mkdir(); //如果不存在,則創(chuàng)建該文件夾
}
}
//處理事件
public void actionPerformed(ActionEvent e)
{
try
{
//在tempPath路徑下創(chuàng)建臨時文件"mytempfileXXXX.tmp"
//XXXX 是系統(tǒng)自動產生的隨機數, tempPath對應的路徑應事先存在
File tempFile = File.createTempFile("mytempfile", ".txt", tempPath);
System.out.println(tempFile.getAbsolutePath());
FileWriter fout = new FileWriter(tempFile);
PrintWriter out = new PrintWriter(fout);
out.println("some info!" );
out.close(); //注意:如無此關閉語句,文件將不能刪除
//tempFile.delete();
tempFile.deleteOnExit();
}
catch(IOException e1)
{
System.out.println(e1);
}
}
}
效果圖:
點擊創(chuàng)建臨時文件效果圖:
非常簡單實用的功能,希望小伙伴們能夠喜歡。