Temporary files

suggest change

Temporary files and directories are frequently needed for caching, file uploads, intermediate processing results, or unit testing. Java provides two primary APIs for temporary file operations: the modern java.nio.file.Files API (introduced in Java 7 and recommended for all new code) and the legacy java.io.File.createTempFile API.

Modern NIO.2: Files.createTempFile

The java.nio.file.Files utility class provides thread-safe, atomic, and secure methods to create temporary files and directories.

Creating a Temporary File in the System Temp Directory

By default, temporary files are created inside the OS temporary directory (/tmp on Linux/macOS or C:\Users\<user>\AppData\Local\Temp on Windows):

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

public class TempFileExample {
    public static void main(String[] args) throws IOException {
        // Prefix "upload_", suffix ".tmp"
        Path tempFile = Files.createTempFile("upload_", ".tmp");

        System.out.println("Temporary file path: " + tempFile.toAbsolutePath());

        // Write data
        Files.writeString(tempFile, "Temporary payload content");

        // Read data back
        String content = Files.readString(tempFile);
        System.out.println("Read: " + content);

        // Explicit deletion
        Files.deleteIfExists(tempFile);
    }
}

Specifying a Custom Directory

You can specify a parent directory where the temporary file should reside:

Path customDir = Path.of(System.getProperty("user.home"), "scratch");
Files.createDirectories(customDir);

Path tempFile = Files.createTempFile(customDir, "job-", ".csv");

Creating Temporary Directories

Use Files.createTempDirectory when an operation requires working with multiple temporary files:

import java.io.IOException;
import java.nio.file.*;
import java.util.Comparator;
import java.util.stream.Stream;

public class TempDirExample {
    public static void main(String[] args) throws IOException {
        Path tempDir = Files.createTempDirectory("worker_batch_");

        try {
            Path file1 = Files.createTempFile(tempDir, "chunk_1_", ".bin");
            Path file2 = Files.createTempFile(tempDir, "chunk_2_", ".bin");
            System.out.println("Created temp directory: " + tempDir);
        } finally {
            // Recursively clean up directory and all files inside
            deleteDirectoryRecursively(tempDir);
        }
    }

    private static void deleteDirectoryRecursively(Path dir) throws IOException {
        if (!Files.exists(dir)) return;
        try (Stream<Path> walk = Files.walk(dir)) {
            walk.sorted(Comparator.reverseOrder())
                .forEach(path -> {
                    try {
                        Files.deleteIfExists(path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
        }
    }
}

Safe Cleanup with AutoCloseable

A best practice is encapsulating temporary file lifecycle within a try-with-resources block using a custom wrapper:

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

public class TempFileHandle implements Closeable {
    private final Path path;

    public TempFileHandle(String prefix, String suffix) throws IOException {
        this.path = Files.createTempFile(prefix, suffix);
    }

    public Path getPath() {
        return path;
    }

    @Override
    public void close() throws IOException {
        Files.deleteIfExists(path);
    }
}

// Usage:
try (var handle = new TempFileHandle("export-", ".json")) {
    Files.writeString(handle.getPath(), "{\"status\": \"ok\"}");
    // File is guaranteed to be deleted when exiting this block
}

Legacy API: File.createTempFile and deleteOnExit()

In older Java codebases, you may encounter java.io.File:

import java.io.File;
import java.io.IOException;

public class LegacyTempFile {
    public static void main(String[] args) throws IOException {
        // Prefix must be at least 3 characters long
        File temp = File.createTempFile("legacy_", ".txt");

        // Requests that the file be deleted when the JVM terminates normally
        temp.deleteOnExit();

        System.out.println("Temp file created: " + temp.getAbsolutePath());
    }
}

[!WARNING] Use deleteOnExit() with caution:

  • The file is only deleted on normal JVM termination, not on SIGKILL or abrupt halts.
  • The JVM holds references to all deleteOnExit() paths in memory until exit, which can cause memory leaks in long-running applications or servers creating many temporary files. Always prefer explicit deletion in a finally block or try-with-resources.

Security and File Permissions

On POSIX platforms (Linux, macOS), Files.createTempFile automatically applies strict file permissions (0600, readable and writable only by the owner) to prevent unauthorized local users from reading or tampering with temporary data.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents