Create Directory in Java

With the help of File IO API in Java, you can create a single directory or multiple directories in the disk. Here I wrote a very simple example to demonstrate the use of File class and create the directories.

  • mkdir – Creates a directory
  • mkdirs – Creates multiple directories

Create Directory Example

CreateDirectoryDemo.java

package javabeat.net.core;

import java.io.File;

public class CreateDirectoryDemo {
	public static void main(String[] args) {
		File sampleDir = new File("C:\\SampleDir");
		if (!sampleDir.exists()) {
			if (sampleDir.mkdir()) {
				System.out.println("Sample Directory is created!");
			} else {
				System.out.println("Could not create directory!");
			}
		}

		File dirFiles = new File("C:\\SampleDir2\\AnotherDir\\AnotherDir");
		if (!dirFiles.exists()) {
			if (dirFiles.mkdirs()) {
				System.out.println("All the directories are created!");
			} else {
				System.out.println("Failed to create directories!");
			}
		}

	}
}

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*