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!

Top Hashtags:

Advertisements

Advertisements




Advertisements