How to Create a Temporary File in Java

There are times when we need to create temporary files on the fly to store some information and delete them afterwards.

In Java, we can use Files.createTempFile() methods to create temporary files.

Create Temporary Files

The following example uses Files.createTempFile(prefix, suffix) to create a temporary file.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CreateTempFile {

    public static void main(String[] args) {

        try {
            // Create a temporary file
            Path tempFile = Files.createTempFile("temp-", ".txt");
            System.out.println("Temp file : " + temp);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Temp file : /var/folders/nyckvw0000gr/T/temp-2129139085984899264.txt

Here, the “temp-“ is the prefix and “.text” is the suffix.

If the suffix is null, the temporary file is created with .tmp extension.

For example:

Path tempFile = Files.createTempFile("prefix-", null);
System.out.println("Temp file : " + tempFile);
// Temp file : /var/folders/nyckvw0000gr/T/prefix-17184288103181464441.tmp

Also if the suffix is not provided a temp file is created with no extension:

Path tempFile = Files.createTempFile(null, "");
System.out.println("Temp file : " + tempFile);
// Temp file : /var/folders/nyckvw0000gr/T/1874152090427250275

Create a Temp File in a Specified Directory

Rather than letting Java choose the directory, we can tell it where to create the temporary file.

For example:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateTempFile {

    public static void main(String[] args) {

        try {
            Path path = Paths.get("target/tmp/");

            // Create a temporary file in the specified directory.
            Path tempFile = Files.createTempFile(path, null, ".log");
            System.out.println("Temp file : " + temp);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Create a Temp File and Write to it

The following code example creates a temporary file and then writes some text to it:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateTempFile {

    public static void main(String[] args) {

        try {
            Path path = Paths.get("target/tmp/");

            // Create an temporary file in a specified directory.
            Path tempFile = Files.createTempFile(path, null, ".log");
            System.out.println("Temp file : " + tempFile);

            // write a line
            Files.write(tempFile, "Hello From Temp File\n".getBytes(StandardCharsets.UTF_8));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}