Java Files.createDirectories and createDirectory
Create a folder with an existing parent or create all missing parents in a chain.
A simple example
Files.createDirectories and createDirectory
- Start with An empty practice folder
- Do this Create a/b including parents
- Result Both directories exist
Syntax
public static Path createDirectories(Path dir, FileAttribute<?>... attrs) throws IOException
JDK 21 declarations (2)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPrepare the monthly payroll folders
A payroll job runs at the start of each month and may be retried after a restart. Create its department directory once and use a repeatable operation for the nested year and month folders.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path pay = Files.createDirectory(desk.resolve("payroll"));
Path month = pay.resolve("2026").resolve("March");
Files.createDirectories(month);
System.out.println(Files.isDirectory(Files.createDirectories(month)));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true
The second call to createDirectories accepts the existing month directory.
Handle a filename in the folder's place
A monthly export expects to create a directory named March. This time an earlier upload is a regular file with that name, so the export must preserve it and report the conflict.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path month = Files.writeString(desk.resolve("March"), "original");
try {
Files.createDirectories(month);
} catch (FileAlreadyExistsException e) {
System.out.println(Files.readString(month));
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
original
An existing file is not an acceptable directory. Its contents are still intact after the failure.
Locate a rehearsal score
The choir stores each score inside a season folder. Create the named season or class folder and its proofs subfolder in an empty workspace. What state should the operator see after successful creation?
What to watch for
createDirectory fails if the target already exists. createDirectories can be repeated when the existing destination is a directory.
Documentation for Files.createDirectories and createDirectory