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) |