Java Create Directory with Files.createDirectory()

The Java Files.createDirectory() creates a new directory. If a file already exists, a FileAlreadyExistsException is thrown.

Java creates a directory with Files.createDirectory

The example creates a new directory with Files.createDirectory().
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavaCreateDirectory {

    public static void main(String[] args) throws IOException {

        String fileName = "/home/ramesh/tmp/newdir";

        Path path = Paths.get(fileName);

        if (!Files.exists(path)) {
            
            Files.createDirectory(path);
            System.out.println("Directory created");
        } else {
            
            System.out.println("Directory already exists");
        }
    }
}
A Path is created from the file name. A Path is a Java object used to locate a file in a file system.
String fileName = "/home/ramesh/tmp/newdir";

Path path = Paths.get(fileName);
We first check if the directory does not already exist with Files.exists():
if (!Files.exists(path)) {
The directory is created with Files.createDirectory(). The method takes a path object as a parameter:
Files.createDirectory(path);

Comments