Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7484
  • 博文数量: 7
  • 博客积分: 125
  • 博客等级: 入伍新兵
  • 技术积分: 50
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-06 11:02
文章分类

全部博文(7)

文章存档

2014年(1)

2013年(1)

2012年(5)

我的朋友
最近访客

分类: Java

2012-11-08 20:17:51

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.
  
  package org.hello.i;
  
  import java.io.BufferedReader;
  
  import java.io.BufferedWriter;
  
  import java.io.File;
  
  import java.io.FileReader;
  
  import java.io.FileWriter;
  
  import java.io.IOException;
  
  public class JavaTempFile {
  
  public static void main(String[] args){
  
  try{
  
  //create a temp file
  
  File temp = File.createTempFile(“temp-file-name”, “.tmp”);
  
  System.out.println(“Temp File: ”+ temp.getAbsolutePath());
  
  //write content to it
  
  BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
  
  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.”);
  
  bw.close();
  
  System.out.println(“Content has been writen ”);
  
  //read it
  
  BufferedReader br = new BufferedReader(new FileReader(temp));
  
  System.out.println(“Content: ”+ br.readLine());
  
  br.close();
  
  //Get tempropary file path
  
  String absolutePath = temp.getAbsolutePath();
  
  String tempFilePath = absolutePath.substring(0,absolutePath.lastIndexOf(File.separator));
  
  System.out.println(“Temp file path : ” + tempFilePath);
  
  //delete temporary file when the program is exited
  
  temp.deleteOnExit();
  
  //delete immediate
  
  //temp.delete();
  
  }catch(IOException e){
  
  e.printStackTrace();
  
  }
  
  }
  
  }
  
  运行结果:
  
  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
阅读(393) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~