Create a temporary file through Java's File class, and then automatically delete the temporary file when the program exits. The following will create a JFrame interface, click the Create button to create a temp folder under the current directory and create a text file in mytempfile******.tmp format. The code is as follows:
The code copy is as follows:
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Function: Create temporary files (under the specified path)
*/
public class TempFile implements ActionListener
{
private File tempPath;
public static void main(String args[]){
TempFile ttf = new TempFile();
ttf.init();
ttf.createUI();
}
//Create a UI
public void createUI()
{
JFrame frame = new JFrame();
JButton jb = new JButton("Create temporary file");
jb.addActionListener(this);
frame.add(jb,"North");
frame.setSize(200,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//initialization
public void init(){
tempPath = new File("./temp");
if(!tempPath.exists() || !tempPath.isDirectory())
{
tempPath.mkdir(); //If it does not exist, create this folder
}
}
//handle events
public void actionPerformed(ActionEvent e)
{
try
{
//Create the temporary file "mytempfileXXXX.tmp" under the tempPath path
//XXXX is a random number automatically generated by the system. The path corresponding to tempPath should exist in advance.
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(); //Note: If there is no such closing statement, the file will not be deleted.
//tempFile.delete();
tempFile.deleteOnExit();
}
catch(IOException e1)
{
System.out.println(e1);
}
}
}
Reproduction image:
Click to create temporary file rendering:
Very simple and practical functions, I hope you can like it.