Files Create Directories Idempotent

Files.createDirectory throws NoSuchFileException when a parent is missing, while createDirectories fills each level and is safe to call twice.

JavaFile Upload

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;

public class FilesCreateDirectoriesIdempotent {

    public static void main(String[] args) throws IOException {
        Path root = Files.createTempDirectory("uploads-");
        Path nested = root.resolve("2026/11/19");

        // createDirectory:父目录不存在直接抛 NoSuchFileException
        try {
            Files.createDirectory(nested);
        } catch (IOException e) {
            System.out.println("createDirectory failed: " + e.getClass().getSimpleName());
        }

        // createDirectories:逐级补齐,目录已存在也静默通过(幂等)
        Files.createDirectories(nested);
        Files.createDirectories(nested);
        System.out.println("nested is a directory: " + Files.isDirectory(nested));

        // 清理演示目录:逆序删除保证子项先于父项
        try (var paths = Files.walk(root)) {
            paths.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
        }
        System.out.println("root still exists: " + Files.exists(root));
    }
}

How the snippet works

Everything happens inside the class FilesCreateDirectoriesIdempotent.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

What to watch for

  • Any imports present resolve to standard-library modules.

Applying it

The run emits 3 labeled sections — createDirectory failed:, nested is a directory:, root still exists: — one per step.

Statements that do the work

paths.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
Path root = Files.createTempDirectory("uploads-");
Path nested = root.resolve("2026/11/19");

FAQ

What does Files Create Directories Idempotent print when run?
Run it as a complete program — the output lines carry labels such as `createDirectory failed:`, `nested is a directory:`, `root still exists:`.