Create Nested Directories using Java Code

Create Nested Directories using Java Code

In order to create nested directories we can make use of the Files.createDirectories() that was added in Java 7.

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

public class JavaCreateDirectoryExample {
    public static void main(String[] args) {
        String nestedDirectories = "myDir1/myDir2/myDir3/myDir4";
        String pathStr = "/Users/code2care/my-projects-22/java-examples/";
        Path dirPathAndName = Paths.get(pathStr+nestedDirectories);
        try {
            Path path = Files.createDirectories(dirPathAndName);
            System.out.println("Nested Directories created: " + path);
        } catch (IOException e) {
            System.out.println("Error occurred while creating Directories!...");

Nested Directories created: /Users/code2care/my-projects-22/java-examples/myDir1/myDir2/myDir3/myDir4

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap