Java Files createTempDirectory() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, Files.createTempDirectory(prefix) creates a brand-new, empty folder with a unique name (the prefix plus a random number) in the system temp location and returns its path.

It is the safest place for experiments, tests, and intermediate files, because nothing else uses that folder. It is not deleted automatically: when you are done, delete its contents and then the folder.

A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.createTempDirectory(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Give a prefix, and optionally the parent folder:

Java
Path work = Files.createTempDirectory("demo");          // e.g. demo4471230983
Path job = Files.createTempDirectory(work, "job-");      // inside work
Path any = Files.createTempDirectory(null);              // digits only
CallWhat it does
createTempDirectory(prefix)New folder in java.io.tmpdir.
createTempDirectory(dir, prefix)New folder inside an existing dir.
createTempDirectory(prefix, attr)Also applies attributes, e.g. POSIX permissions.

Since Java 7. On Linux and macOS the folder gets owner-only permissions (rwx------), so other users cannot look inside. Every example on these pages starts with this call.

Library declarations
Java
public static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) throws IOException
public static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) throws IOException

Parameters

ParameterDescription
dir(Second overload) Existing folder to create the new folder in.
prefixStart of the generated name, or null.
attrsOptional attributes applied while creating.

Return Value

Return ValueDescription
PathThe new, empty directory. The name is random, so avoid printing it.

Compare with Similar Methods

Related ways to get a working folder:

MethodHow it differs
createTempFile()A single temp file instead of a folder.
createDirectories()A folder with a name you choose; may already exist.
walk()Lists the whole tree, useful for deleting it again.

Java Examples

Example 1 — Create a Scratch Folder and Check It

Create a temp folder, confirm it is an empty directory with the expected prefix, and delete it.

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

public class CreateTempDirectoryBasic {
    public static void main(String[] args) throws IOException {
        Path work = Files.createTempDirectory("demo");
        System.out.println("Is a directory: " + Files.isDirectory(work));
        System.out.println("Name starts with demo: " + work.getFileName().toString().startsWith("demo"));
        boolean empty;
        try (DirectoryStream<Path> entries = Files.newDirectoryStream(work)) {
            empty = !entries.iterator().hasNext();
        }
        System.out.println("Empty: " + empty);
        Files.delete(work);
        System.out.println("Deleted: " + Files.notExists(work));
    }
}

How It Works

  1. Prefix plus random digits. The folder name begins with demo, followed by a number chosen to be unique, which is why only the prefix is checked.
  2. Peek inside. A DirectoryStream, closed by try-with-resources, has no first entry, so the folder is empty.
  3. Empty folders delete directly. With nothing inside, one Files.delete removes it, and notExists confirms.

Example 2 — One Temp Folder per Job

Use the overload with a parent folder to give each job its own uniquely named folder inside a shared base.

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

public class CreateTempDirectoryJobs {
    public static void main(String[] args) throws IOException {
        Path base = Files.createTempDirectory("demo");
        Path job1 = Files.createTempDirectory(base, "job-");
        Path job2 = Files.createTempDirectory(base, "job-");
        System.out.println("job1 inside base: " + job1.getParent().equals(base));
        System.out.println("job2 inside base: " + job2.getParent().equals(base));
        System.out.println("Different names: " + !job1.getFileName().equals(job2.getFileName()));
        boolean prefixOk = job1.getFileName().toString().startsWith("job-")
                && job2.getFileName().toString().startsWith("job-");
        System.out.println("Both start with job-: " + prefixOk);
        Files.delete(job1);
        Files.delete(job2);
        Files.delete(base);
    }
}

How It Works

  1. A base for the run. The first call creates a demo folder in the system temp location.
  2. Children with the same prefix. Both job folders use job- but receive different random numbers, so they never clash even when created back to back.
  3. Parent check. getParent() of each job folder equals base, proving the overload placed them inside it.

Example 3 — Fill a Workspace, Then Remove Everything

Create nested content, then delete the whole tree by walking it and sorting paths so children come before their folders.

Java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CreateTempDirectoryCleanup {
    public static void main(String[] args) throws IOException {
        Path work = Files.createTempDirectory("demo");
        Path main = Files.createDirectories(work.resolve("src").resolve("main"));
        Files.write(main.resolve("App.java"), "class App {}".getBytes(StandardCharsets.UTF_8));
        Files.write(work.resolve("README.txt"), "demo".getBytes(StandardCharsets.UTF_8));
        List<Path> all;
        try (Stream<Path> tree = Files.walk(work)) {
            all = tree.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }
        for (Path p : all) {
            Files.delete(p);
            String rel = work.relativize(p).toString().replace('\\', '/');
            System.out.println("deleted " + (rel.isEmpty() ? "(workspace)" : rel));
        }
        System.out.println("Workspace gone: " + Files.notExists(work));
    }
}

How It Works

  1. Five entries. The workspace holds src, src/main, App.java, and README.txt, plus the workspace folder itself.
  2. Reverse path order. A path sorts after its own folder, so Comparator.reverseOrder() puts every child before its parent; README.txt sorts before src because R comes before s.
  3. Delete as you go. Each folder is already empty when it is reached, so plain Files.delete never sees DirectoryNotEmptyException.
  4. The root has an empty name. work.relativize(work) is an empty path, printed here as (workspace).

Frequently Asked Questions

In the folder named by the java.io.tmpdir system property, for example under /tmp on Linux or the user's AppData\Local\Temp folder on Windows, unless you pass a parent directory.
No. Java does not remove it. Delete the contents and then the folder yourself, or the temp location slowly fills up.
Walk it with Files.walk, sort the paths in reverse order so children come first, and delete each one, or use Files.walkFileTree with a visitor that deletes in postVisitDirectory.
Only the prefix. The rest is a random number that keeps the name unique. Use createDirectory or createDirectories if you need an exact name.
On Linux and macOS the folder is created with owner-only permissions, rwx------. On Windows it inherits the permissions of its parent folder.

Next: Files.createTempFile()

Create a new empty file with a unique random name in the temp folder or a folder you choose.

createTempFile() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful