How to create directories recursively in Java

Java can create a tree structure of directories like mkdir -p in linux using the mkdirs method of the File Object.

Call the following method:

	new File("PATH").mkdirs();

This code example create a new File Object that have the path V:/tmp/a/a/a. This is basically 4 directories containing each other. The mkdirs method will create the directory structure and add a directory if it doesn't already exist.

Create the following java file:

import java.io.File;

public class DirectoriesCreate {

    public static void main(String[] argv) {

	File file = new File("V:/tmp/a/a/a");

	try{
	    boolean result = file.mkdirs();
	    if (result)
		System.out.print( "Directories created" );
	    else
		System.out.print( "Directories not created" );
	} catch (SecurityException e) {
	    e.printStackTrace();
	}
    }

}

The output will be:

Directories created

The directory are created as the Java user. It is important to check that the user has access and write access to create the directories.

References:

java io

Recent Comments