Create a Directory using Java Code


In order to create a directory (folder) using Java code we can make use of the createDirectory() method from the Files class that was introduced 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 dirName = "myDir";
        String pathStr = "/Users/code2care/my-projects-22/java-examples/";
        Path dirPathAndName = Paths.get(pathStr+dirName);
        try {
            Path path = Files.createDirectory(dirPathAndName);
            System.out.println("Directory created: " + path);
        } catch (IOException e) {
            System.out.println("Error occurred while creating directory!...");
            e.printStackTrace();
        }
    }
}
Output:

Directory created: /Users/code2care/my-projects-22/java-examples/myDir

Create Directory using Java Files Class
Create Directory using Java Files Class

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: rakesh@code2care.org



















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