How do I create a temporary file with Files.createTempFile()?

To create a temporary file using java.nio.file.Files.createTempFile, you can use one of two main overloaded methods. This is part of the Java NIO.2 API and is generally preferred over the older File.createTempFile because it returns a Path object and allows for better error handling and file attributes.

1. In the Default Temporary Directory

If you only care about the prefix and suffix, Java will place the file in the system’s default temporary folder.

package org.kodejava.nio;

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

public class TempFileExample {
    public static void main(String[] args) {
        try {
            // Prefix: "log_", Suffix: ".tmp"
            // Result: /tmp/log_123456789.tmp (the path varies by OS)
            Path tempFile = Files.createTempFile("log_", ".tmp");

            System.out.println("Temporary file created at: " + tempFile);

            // Optionally, delete the file on exit (NIO doesn't have a direct 
            // method like File, so we usually use a shutdown hook or delete
            // manually)
            tempFile.toFile().deleteOnExit();

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

2. In a Specific Directory

If you want the temporary file to be created in a specific folder, pass a Path as the first argument.

package org.kodejava.nio;

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

public class CustomTempFileExample {
    public static void main(String[] args) {
        Path customDir = Paths.get("C:/my_app/temp");

        try {
            // Ensure the directory exists first
            if (Files.notExists(customDir)) {
                Files.createDirectories(customDir);
            }

            Path tempFile = Files.createTempFile(customDir, "data_", ".dat");
            System.out.println("File created in custom dir: " + tempFile);

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

Key Differences to Note:

  • Prefix/Suffix: The prefix must be at least three characters long. The suffix can be null, in which case .tmp is used.
  • Security: Files.createTempFile creates the file with restricted permissions (readable/writable only by the owner) by default on many systems, which is more secure than the older File.createTempFile.
  • Return Type: It returns a java.nio.file.Path object, which is the modern way to handle file paths in Java.