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.

Updated:

Comments