Java Create Parent and Sub Directories using Files.createDirectories()

Tags: Files.createDirectories Java NIO

In this Java NIO tutorial we learn how to create parent and sub directories of a file path in Java application using the Files.createDirectories() method.

Table of contents

  1. How to use Files.createDirectories() method
  2. More Files.createDirectories() Java Examples

How to use Files.createDirectories() method

For example, we want to create all parent and sub directories for the path D:\SimpleSolution\Data\Java\JavaNIO , we can use the Files.createDirectories() method as the following Java application.

FilesCreateDirectoriesExample1.java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FilesCreateDirectoriesExample1 {
    public static void main(String... args) throws IOException {
        Path directoryToCreate = Paths.get("D:\\SimpleSolution\\Data\\Java\\JavaNIO");

        Path createdDirectories = Files.createDirectories(directoryToCreate);

        System.out.println("Successful create directories: " + createdDirectories.toString());
    }
}
The output as below.
Successful create directories: D:\SimpleSolution\Data\Java\JavaNIO

More Files.createDirectories() Java Examples

In the following Java program, we use Files.createDirectories() method to create directories inside temporary directory.

FilesCreateDirectoriesExample2.java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FilesCreateDirectoriesExample2 {
    public static void main(String... args) throws IOException {
        Path tempDirectory = Files.createTempDirectory("TestCreateDirectory");
        Path directoryToCreate = tempDirectory.resolve("Simple").resolve("Solution").resolve("Java");

        Path createdDirectories = Files.createDirectories(directoryToCreate);

        System.out.println("Successful create directories: " + createdDirectories.toString());
    }
}
The output as below.
Successful create directories: C:\Users\SS\AppData\Local\Temp\TestCreateDirectory8802687788553334892\Simple\Solution\Java

Happy Coding 😊

Java Copy File using Files.copy()

Java Get All Entries in Directory using Files.newDirectoryStream()

Java Create a New Directory using Files.createDirectory()

Java Create New File using Files.createFile()