How to create directory in Java

To create a directory in Java, uses the following code :

1. Create a single directory.

new File("C:\\Directory1").mkdir();

2. Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.

new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()

Both methods are returning a boolean value to indicate the operation status : true if succeed, false otherwise.


A classic Java directory example, check if directory exists, if no, then create it.

package com.mkyong.file;
public class CreateDirectoryExample
    public static void main(String[] args)
	File file = new File("C:\\Directory1");
	if (!file.exists()) {
		if (file.mkdir()) {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
	File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2");
	if (files.exists()) {
		if (files.mkdirs()) {
			System.out.println("Multiple directories are created!");
		} else {
			System.out.println("Failed to create multiple directories!");
Tags :

About the Author

Founder of and, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.