Video in progress

How do you create nested directories with a single call?

Files.createDirectories(path) creates all the missing directories on the path and doesn't fail if the directory already exists. Files.createDirectory creates only the last one and throws an exception if the parent is missing or the directory exists.

📖 Answer

Path dir = Path.of("uploads", "2026", "11", "03");

Files.createDirectory(dir);    // if uploads/2026/11 doesn't exist: NoSuchFileException
Files.createDirectories(dir);  // creates everything, passes quietly if it exists

In practice, before saving a file you almost always write this:

Path target = baseDir.resolve(fileName);
Files.createDirectories(target.getParent());
Files.write(target, bytes);

In the old API the counterparts are mkdir() and mkdirs(), but they return false instead of throwing and don't tell you why.

createDirectories is safe even if several threads call it at the same time: if someone created the directory before you, it is not an error. Only if there is a regular file, not a directory, at that path do you get FileAlreadyExistsException.