Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2531041
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2011-12-29 10:15:49

Create:
Read& Write:
There are no different between normal file and temporary file, what apply to normal text file, will apply to temporary file as well.

Delete: Temporary file is used to store the less important and temporary data, which should always be deleted when your system is terminated. The best practice is use the File.deleteOnExit() to do it.

  1. package org.hello.i;

  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileReader;
  6. import java.io.FileWriter;
  7. import java.io.IOException;

  8. public class JavaTempFile {

  9.     public static void main(String[] args){
  10.         try{
  11.             //create a temp file
  12.             File temp = File.createTempFile("temp-file-name", ".tmp");
  13.             System.out.println("Temp File: "+ temp.getAbsolutePath());
  14.         
  15.         
  16.             //write content to it
  17.             BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
  18.             bw.write("Actually, there are no different between normal file and temporary file, what apply to normal text file, will apply to temporary file as well.");
  19.             bw.close();
  20.             System.out.println("Content has been writen ");
  21.             
  22.             //read it
  23.             BufferedReader br = new BufferedReader(new FileReader(temp));
  24.             System.out.println("Content: "+ br.readLine());
  25.             br.close();
  26.             
  27.             //Get tempropary file path
  28.             String absolutePath = temp.getAbsolutePath();
  29.             String tempFilePath = absolutePath.substring(0,absolutePath.lastIndexOf(File.separator));
  30.  
  31.             System.out.println("Temp file path : " + tempFilePath);
  32.             
  33.             //delete temporary file when the program is exited
  34.             temp.deleteOnExit();
  35.             
  36.             //delete immediate
  37.             //temp.delete();
  38.             
  39.         }catch(IOException e){
  40.             e.printStackTrace();
  41.         }
  42.     }
  43. }
运行结果:
Temp File: C:\Users\harrypoter\AppData\Local\Temp\temp-file-name2692138736359297894.tmp
Content has been writen
Content: Actually, there are no different between normal file and temporary file, what apply to normal text file, will apply to temporary file as well.
Temp file path : C:\Users\harrypoter\AppData\Local\Temp

阅读(3363) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~