Create temporary files from the Java file class, and then automatically delete temporary files when the program exits. Next, create a temp folder under the current directory and create a text file in mytempfile******.tmp format by creating a JFrame interface. The code is as follows:
Copy Code code as follows:
Import java.io.*;
Import java.util.*;
Import javax.swing.*;
Import java.awt.event.*;
/**
* Function: Create temporary file (under 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 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);
}
Class
public void init () {
TempPath = new File ("./temp");
if (!temppath.exists () | |!temppath.isdirectory ())
{
Temppath.mkdir (); If it does not exist, the folder is created
}
}
Handling Events
public void actionperformed (ActionEvent e)
{
Try
{
Create a temporary file "Mytempfilexxxx.tmp" under the TempPath path
XXXX is the system automatically generated random number, temppath corresponding path 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 you do not have this close statement, the file will not be deleted
Tempfile.delete ();
Tempfile.deleteonexit ();
}
catch (IOException E1)
{
SYSTEM.OUT.PRINTLN (E1);
}
}
}
Effect Chart:
Click Create temporary file Effect chart:
Very simple and practical functions, I hope that small partners can enjoy.