Create New Directory in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO Create File Directory

In this Java tutorial we learn how to create new directories using the FileUtils class of Apache Commons IO library.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

Create New Directory using FileUtils.forceMkdir() method

The method FileUtils.forceMkdir() to make a directory which creates any subdirectories if it does not exist. The following code example shows you how to use the method.

ForceCreateDirectory.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class ForceCreateDirectory {
    public static void main(String... args) {
        try {
            File newDirectory = new File("D:\\TestData\\a\\b\\c");

            FileUtils.forceMkdir(newDirectory);

            System.out.println("Create directories " + newDirectory + " success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Create directories D:\TestData\a\b\c success!

Create New Directory using FileUtils.forceMkdirParent() method

The method FileUtils.forceMkdirParent() to make a directory for the File which creates any nonexistent parent directories of the file. The below code example shows you how to use the method.

ForceCreateParentDirectory.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class ForceCreateParentDirectory {
    public static void main(String... args) {
        try {
            File file = new File("D:\\TestData\\a\\b\\c\\data.txt");

            FileUtils.forceMkdirParent(file);

            System.out.println("Create parent directories of file " + file + " success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Create parent directories of file D:\TestData\a\b\c\data.txt success!

Happy Coding 😊