How to Create a Temporary File in Java


In this example, it will tell us how to create a temporary file named “Test.txt“ and write the source file of this program to this file.

Source Code

package com.beginner.examples;

import java.io.*;
public class WriteTempFileExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			File tem=File.createTempFile("Test","txt");
			FileReader fr=new FileReader("src//com//beginner//examples//WriteTempFileExample.java");
			FileWriter fw=new FileWriter(tem);
			FileWriter fw1=new FileWriter("Codes.txt");
			char[] chs=new char[1024];
			int len=0;
			while((len=fr.read(chs))!=-1)
			{
				fw.write(chs, 0, len);
				fw1.write(chs,0,len);
				fw1.flush();
				System.out.println(new String(chs,0,len));
				
			}
			fw1.close();
			fr.close();
			fw.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}

}

Output:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments