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.io.File;
import java.io.IOException;
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");
            System.out.println(tempFile.getAbsolutePath());
            tempFile.delete();
        } catch (IOException ex) {
            Logger.getLogger(CreateTempFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Executing this sample code provides the following output:

C:\Users\david\AppData\Local\Temp\tmp7041803588749875405.txt

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.

About

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