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.

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!...");

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

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

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


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.