Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to create a folder

Short answer

Files.createDirectories() creates the folder together with any missing parent folders. If the folder already exists, there is no error:

void main() throws IOException {
    Path dir = Path.of("data", "2026", "march");
    Files.createDirectories(dir);
    Files.createDirectories(dir);
 
    IO.println(Files.isDirectory(dir));
}

Output:

true

A single folder

createDirectory() creates only one folder and throws if it already exists:

void main() throws IOException {
    Path dir = Path.of("cache");
    Files.createDirectory(dir);
    IO.println("created");
    Files.createDirectory(dir);
}

Output:

created
Exception in thread "main" java.nio.file.FileAlreadyExistsException: cache

Before writing a file

Create the file's parent folder with getParent():

void main() throws IOException {
    Path file = Path.of("reports", "q1", "summary.txt");
    Files.createDirectories(file.getParent());
    Files.writeString(file, "ok");
 
    IO.println(Files.readString(file));
}

Output:

ok

A temporary folder

createTempDirectory() creates a folder with a unique name in the system's temp folder:

void main() throws IOException {
    Path tmp = Files.createTempDirectory("import-");
    IO.println(tmp.getFileName());
}

Output:

import-12662471789010885702

The name is new each time.

Common mistake

Building a path by gluing strings with "/" or "\\". Windows and Linux use different separators. Path.of("data", "2026") and path.resolve("file.txt") use the right separator for you.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.