TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
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.
- 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:UsersharrypoterAppDataLocalTemp emp-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:UsersharrypoterAppDataLocalTemp
源码下载:http://file.javaxxz.com/2014/11/2/235823250.zip |
|