Create Nested Folders with Java

With the new Java NIO (New IO, introduced with Java 1.4) API you can create a nested directory structure with basically one line of code with the createDirectories method (we declare the path in an additional variable which can be omitted):

import java.nio.file.Files;
import java.nio.file.Path;

var path = Path.of("devlabs/ninja/rocks");
Files.createDirectories(path);

If you call this code from a main method, the "devlabs/ninja/rocks" folders structure will be created starting from the current directory.

The NIO API was designed to support I/O operations on channels and buffers instead of streams, which is more efficient in certain scenarios.

Another more explicit example for the case if your input is provided in a string array and also the root directory is in a string variable:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateNestedFolders {
    public static void main(String[] args) {
        String baseFolder = "C:\\example";
        String[] subFolders = {"devlabs", "ninja", "rocks"};

        Path basePath = Paths.get(baseFolder);
        try {
            Files.createDirectories(basePath);
            for (String subFolder : subFolders) {
                Path subPath = basePath.resolve(subFolder);
                Files.createDirectories(subPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

It's worth noting that Files.createDirectories throws an IOException if a directory cannot be created because the parent directory does not exist or some other reason, so it's a good practice to wrap it in a try-catch block.

And for the sake of completeness, an example that doesn't use the Java NIO API:

import java.io.File;

public class CreateNestedFolders {
    public static void main(String[] args) {
        String baseFolder = "C:\\example";
        String[] subFolders = {"devlabs", "ninja", "rocks"};

        File file = new File(baseFolder);
        file.mkdir();

        for (String subFolder : subFolders) {
            file = new File(baseFolder + File.separator + subFolder);
            file.mkdir();
        }
    }
}

Note that File.separator is used to separate folder names. This is because different operating systems use different separators (Windows uses , while Linux and macOS use /). Using the File.separator ensures that the code works on all operating systems.