Java I/O How to - Create a temporary file








Question

We would like to know how to create a temporary file.

Answer

import java.io.File;
public class MainClass {
  public static void main(String[] a) throws Exception {
    File tmp = File.createTempFile("foo", "tmp");
    System.out.println("Your temp file is " + tmp.getCanonicalPath());
  }
}

Create temporary file with specified extension suffix

import java.io.File;
//from ww w  .j  a v a  2  s.co m
public class Main {

  public static void main(String[] args) throws Exception {
    File file1 = null;
    File file2 = null;
    file1 = File.createTempFile("JavaTemp", null);
    file2 = File.createTempFile("JavaTemp", ".java");

    System.out.println(file1.getPath());
    System.out.println(file2.getPath());
  }
}

Create temporary file in specified directory

/*from  w  w w  .jav  a 2  s . com*/
import java.io.File;

public class Main {

  public static void main(String[] args) throws Exception {
    File file = null;
    File dir = new File("C:/");
    file = File.createTempFile("JavaTemp", ".javatemp", dir);

    System.out.println(file.getPath());

  }

}

The code above generates the following result.