Files.createDirectories Idempotent Mkdirs

Create a missing directory tree with Files.createDirectories, which succeeds silently when the directory exists instead of throwing like createDirectory.

JavaCli Tooling

Code

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

public class OutputLayout {

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

        // 一次性创建整条缺失的父链
        Files.createDirectories(nested);
        System.out.println("created: " + Files.isDirectory(nested));

        // 再跑一遍也不抛异常:目录已存在不算失败,天然幂等
        Files.createDirectories(nested);
        System.out.println("re-run ok: " + Files.isDirectory(nested));

        // 对照:createDirectory 只建最后一级,目标已存在会抛异常
        try {
            Files.createDirectory(base.resolve("2026/11/summary"));
        } catch (IOException alreadyExists) {
            System.out.println("createDirectory threw: " + alreadyExists.getClass().getSimpleName());
        }

        // 清理演示目录树:先删最深层再往上收
        try (var paths = Files.walk(base)) {
            paths.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
        }
    }
}

How the snippet works

The snippet is organized around the class OutputLayout.

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

What to watch for

  • The imports (if any) point only at standard-library modules.

Applying it

The run marks each output line — created:, re-run ok:, createDirectory threw: — when the file runs.

Statements that matter

paths.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
Files.createDirectory(base.resolve("2026/11/summary"));
Path base = Files.createTempDirectory("report-");

Interactive Tools for This Topic

FAQ

What does Files.createDirectories Idempotent Mkdirs print when run?
Running the file directly is enough — expect labeled output lines such as `created:`, `re-run ok:`, `createDirectory threw:`.