Java - Create directory or directories

Posted on November 1, 2016


The File class provides two methods for creating directories in java. These methods are

  • mkdir() - Creates the directory named by this abstract pathname. This method returns true if and only if the directory was created; false otherwise.
  • mkdirs() - Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. This method returns true if and only if the directory was created, along with all necessary parent directories; false otherwise.

Here is an example of directory creation in java.

CreateDirectoryExample.java

package com.boraji.tutorial.io;

import java.io.File;

/**
 * @author imssbora
 * CreateDirectoryExample.java
 * Nov 1, 2016
 */
public class CreateDirectoryExample {
	public static void main(String[] args) {
		
		/*Creating directory*/
		File dirPath1=new File("C:/java");
		if(dirPath1.mkdir()){
			System.out.println("Directory created successfully");
		}else{
			System.out.println("Fail to create directory");
		}
		
		/*Creating directory with parent directory*/
		File dirPath2=new File("C:/java8/IO/examples");
		if(dirPath2.mkdirs()){
			System.out.println("Directories created successfully");
		}else{
			System.out.println("Fail to create directories");
		}
	}
}

Output

Directory created successfully
Directories created successfully