tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > IO > Temp Files

Temp Files 

The following example shows creating temp files in system temp directory as well as user configured directory. The deleteOnExit method is a convenient method to delete unwanted temporary files automatically when JVM exits.

File Name  :  
com/bethecoder/tutorials/io/TempFilesTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class TempFilesTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    try {
      //File.createTempFile("prefix", "suffix");
      //File.createTempFile("prefix", "suffix", directory);
      
      //prefix - The prefix string to be used in generating the file's name; 
      //      must be at least three characters long
      
      //suffix - The suffix string to be used in generating the file's name; may be null, 
      //      in which case the suffix ".tmp" will be used 

      //directory - The directory in which the file is to be created, or null 
      //      if the default temporary-file directory is to be used 

      
      File tmpfile = File.createTempFile("name"".ext");
      tmpfile.deleteOnExit();
      System.out.println(tmpfile.getAbsolutePath());
      
      tmpfile = File.createTempFile("mytempfile"null);
      tmpfile.deleteOnExit();
      System.out.println(tmpfile.getAbsolutePath());
      
      //Creates a temp file in the given directory
      tmpfile = File.createTempFile("mytempfile"".txt"new File("C:\\NEW"));
      tmpfile.deleteOnExit();
      System.out.println(tmpfile.getAbsolutePath());
      
      //Write to temp file
      BufferedWriter writer = new BufferedWriter(new FileWriter(tmpfile));
      writer.write("Hello World");
      writer.close();
      
    catch (IOException e) {
      e.printStackTrace();
    }
  }

}
   

It gives the following output,
C:\DOCUME~1\VSUDHA~1\LOCALS~1\Temp\name64728.ext
C:\DOCUME~1\VSUDHA~1\LOCALS~1\Temp\mytempfile64729.tmp
C:\NEW\mytempfile64730.txt



 
  


  
bl  br