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!");
			}
		}

	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!