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!

Top Hashtags: