Recursively create directory

Viewed 68894

Does anyone know how to use Java to create sub-directories based on the alphabets (a-z) that is n levels deep?

 /a
    /a
        /a
        /b
        /c
        ..
    /b
        /a
        /b
        ..
    ..
        /a
        /b
        /c
        ..

/b
    /a
        /a
        /b
        ..
    /b
        /a
        /b
        ..
    ..
        /a
        /b
        ..
..
    /a
        /a
        /b
        ..
    /b
        /a
        /b
        ..
    ..
        /a
        /b
        ..
10 Answers

Since Java 7, java.nio is preferred

import java.nio.file.Files;
import java.nio.file.Paths;

...

Files.createDirectories(Paths.get("a/b/c"));

If you're using mkdirs() (as suggested by @Zhile Zou) and your File object is a file and not a directory, you can do the following:

// Create the directory structure
file.getParentFile().mkdirs();

// Create the file
file.createNewFile();

If you simply do file.mkdirs() it will create a folder with the name of the file.

Apache commons addresses most of these. Try -

org.apache.commons.io.FileUtils.forceMkdir(directory);

Related