Java Create Directory Example

In this source code example, we show you how to create a directory in Java.

We use Files.createDirectory() method to create a new directory. If a file already exists, a FileAlreadyExistsException is thrown.

Java Create Directory Example

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 = "src/resources/sample.txt";
Path path = Paths.get(fileName); if (!Files.exists(path)) { Files.createDirectory(path); System.out.println("Directory created"); } else { System.out.println("Directory already exists"); } } }