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.

Example

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

package com.mkyong.file;
 
import java.io.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

mkyong
Founder of Mkyong.com and HostingCompass.com, 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.

Comments

  • http://www.cprogramto.com/ akshay

    Very easy program to create folder at specified path. Thanks

  • Dariusz

    hi
    you are missing an exclamation mark in the multiple directories
    it should be

    File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2");
    	if (<b>!</b>files.exists()) {
    		if (files.mkdirs()) {

    Could you delete other two posts thanks ;)

  • Dariusz

    hi
    you are missing an exclamation mark in the multiple directories
    it should be

    File files = new File(“C:\\Directory2\\Sub2\\Sub-Sub2″);
    if (!files.exists()) {
    if (files.mkdirs()) {

  • Dar

    hi
    you are missing an exclamation mark in the multiple directories
    it should be

    File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2");
    	if (<bold>!</bold>files.exists()) {
    		if (files.mkdirs()) {
  • Mezbah uddin

    Really awesome site for java learner but filling the lackings of the tutorial for javax.swing.Its request to sir consider our demand.

  • http://www.edu-computer.ir aboulfazl

    thanks very much

  • Shruthi

    Very Useful. Thank you very much

  • Madhumitha

    All of your posts are of great help. Thanks. Continue writing more tech posts :)

  • pravin

    i like it but give some video to how to create directory

  • anupam ghos

    Hi Mkyoung,
    Thank you for your posts. These are really helpful.
    Regards
    Anupam

  • Pingback: Java I/O Tutorial()