Share on Google+Share on Google+

Java file create temp file

Advertisement
This section illustrates you how to generate a temporary file.

Java file create temp file

This section illustrates you how to generate a temporary file.

Description of code:

A temporary file stores information temporarily to free the memory for other purposes. You can use this temporary file to store the content or various information which may be required again during the execution of the application. It is beneficial and secure to prevent loss of data and  increases the efficiency of the application.

In the given example we have used createTempFile() method to create an empty temporary file. We have used BufferedWriter class to write some text into it. Then we have used the method getAbsolutePath to find the location of temporary file.

Here is the code:

import java.io.*;

public class CreateTempFile {
	public static void main(String[] argv) throws Exception {
		File temp = File.createTempFile("file", ".tmp");
		BufferedWriter out = new BufferedWriter(new FileWriter(temp));
		out.write("Hello World");
		out.close();
		System.out.println(temp.getAbsolutePath());
	}
}

Through the use of createTempFile() method, you can create an empty temporary file.

Output:

C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\file46812.tmp

Advertisements

Posted on: August 1, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.