Creating a Temporary File

Login | Register

Creating a Temporary File

Temporary files can be created in Java using the createTempFile method of the File class.

For example:

import java.util.logging.Level;
import java.util.logging.Logger;
public class CreateTempFile {
    public static void main(String[] args) {
        try {
            File tempFile = File.createTempFile("tmp", ".txt");
        } catch (IOException ex) {
            Logger.getLogger(CreateTempFile.class.getName()).log(Level.SEVERE, null, ex);

Executing this sample code provides the following output:


The first parameter to getTempFile specifies the prefix for the temporary file name, whereas the second parameter specifies the suffix for the temporary file name.


At Develop In Java, we've been a part of the Java community for over 10 years. If there's anything you'd like us to cover, just ask !

Current versions

  • Java - 1.8
  • Java EE - 7
  • Spring - 4.x