Home Java Beginners Creating a temporary file



Creating a temporary file
Posted on: June 7, 2007 at 12:00 AM
In this section, you will learn how to create the temporary file in java.

Java Temporary File - Temporary File Creation in Java

     

In this program we are going to make a temporary file, which will be deleted automatically by the garbage collector when the program ends.

In this program we are using following methods:

createTempFile(String prefix, String suffix): This is a static method of file class. This creates an empty file and we have used two parameters to generate name.

write(): It will write in String.

close(): When we don't need to write further, we should close the program with() that will close the string.

deleteOnExit(): It will delete the existing file when you close the java program or your JVM.

Code of this program is given below:

import java.io.*;

public class CreateTemporaryFile{
  CreateTemporaryFile(){
  }
  public static void CreateTempFile(){
  try{
  // Create a temporary file object
  File tempFile = File.createTempFile("prefix""suffix");
  System.out.println("\nTemporary file file has 

been created : " + tempFile + "\n");
  // Write to temporary file
  BufferedWriter out = new BufferedWriter(new 

FileWriter(tempFile));
  out.write("You are writing on temporary file 

which will delete on exit : " + tempFile);
  out.close();
 // Delete temp file when program exits
  tempFile.deleteOnExit();
  
  catch (IOException e){
  System.out.println("Exception is" + e);
  }
  }
  public static void main(String[] args){
  CreateTempFile();
  }

}

The output of this program is given below:

C:\ CreateTemporaryFile>java CreateTemporaryFile

Temporary file file has been created : C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\prefix3
2276suffix


C:\tapan>

Download this example

Related Tags for Creating a temporary file:
cstringfileclassstaticparametersdeletemethodsmakemethodsedparameternameusingthiscreateemptycallprogramtoautomaticramicaltemporaryprefixrefgenerateautoeilffitempfileuseinrarcalasstampartrtempcaletclesemendautomaticallyallagemeproptyrateparamtorwhenwhichssudelctorcolbagatkishallmeteromacollectmpfpregofolloweaandarstatcollectstrsuffixwinguftwssriringtempothavstarbatictoendsfixgagarbageendsicaicaprndodsomogrolo


Ask Questions?    Discuss: Creating a temporary file   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.