Java implementation creates temporary files and then automatically deletes files when the program exits _java

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.