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.

Example:
import java.io.IOException;
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!...");
            e.printStackTrace();
        }
    }
}
Output:

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



Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.