Library contents

Java Files temporary files and folders

Create unique scratch directories and files for a task.

A simple example

Files temporary files and folders

  1. Start with A temporary workspace
  2. Do this Create two independent temporary items
  3. Result Distinct items
Each creation obtains its own temporary location. This lets examples run without overwriting one another.

Syntax

Java syntax
public static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) throws IOException
JDK 21 declarations (4)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Isolate two exam previews

An examination office renders several versions of the same paper. Each render needs a fresh draft filename under a private work folder even when two previews use exactly the same title.

First output linetrue
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Path batch = Files.createTempDirectory(desk, "exam-");
            Path first = Files.createTempFile(batch, "paper-", ".pdf");
            Path second = Files.createTempFile(batch, "paper-", ".pdf");
            System.out.println(!first.equals(second));
            System.out.println(first.getParent().equals(batch));
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
true
true

The system supplies distinct filenames and both drafts stay inside the designated batch.

Advertisements

Keep a preview's file extension

A classroom image viewer selects its decoder partly from a file suffix. Create two temporary thumbnails with the expected extension and verify the naming contract without hard-coding the system's random names.

First output linetrue
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Path a = Files.createTempFile(desk, "thumb-", ".png");
            Path b = Files.createTempFile(desk, "thumb-", ".png");
            System.out.println(a.getFileName().toString().endsWith(".png"));
            System.out.println(!a.equals(b));
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
true
true

The requested suffix is retained while the generated names distinguish the two files.

Locate a rehearsal score

The choir stores each score inside a season folder. Two students use distinct temporary workspaces with the same filename. Does a file saved by the first student appear in the second student’s workspace?

Givenspring / alto.txt
Worked resultSeparate

What to watch for

Keep the returned path and release open handles before cleanup. Deleting files in a shared temporary directory by guessed names can affect other jobs.

Documentation for Files temporary files and folders