zoukankan      html  css  js  c++  java
  • java实现创建临时文件然后在程序退出时自动删除文件(转)

      这篇文章主要介绍了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 }

    效果图:

    点击创建临时文件效果图:

      非常简单实用的功能,希望小伙伴们能够喜欢。

  • 相关阅读:
    HDU1813:Escape from Tetris(IDA)
    开发汉澳sinox64位,对接汉澳矩阵电脑
    新博客有了,文章转移到 http://www.iosxxx.com/
    Linux内核之于红黑树and AVL树
    MySQL用户及数据安全专题
    实现Android操作系统11种传感器介绍
    NSSCanner 提取 指定 字符串
    [置顶] 正则表达式应用:匹配IP地址
    某APK中使用了动态注册BroadcastReceiver,Launcher中动态加载此APK出现java.lang.SecurityException异常的解决方法
    JSTL解析——003——core标签库02
  • 原文地址:https://www.cnblogs.com/haw2106/p/10280967.html
Copyright © 2011-2022 走看看