How to create a directory in Java?

JavaDirectory

Java Problem Overview


How do I create Directory/folder?

Once I have tested System.getProperty("user.home");

I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.

Java Solutions


Solution 1 - Java

new File("/path/directory").mkdirs();

Here "directory" is the name of the directory you want to create/exist.

Solution 2 - Java

After ~7 year, I will update it to better approach which is suggested by Bozho.

File theDir = new File("/path/directory");
if (!theDir.exists()){
    theDir.mkdirs();
}

Solution 3 - Java

With Java 7, you can use Files.createDirectories().

For instance:

Files.createDirectories(Paths.get("/path/to/directory"));

Solution 4 - Java

You can try FileUtils#forceMkdir

FileUtils.forceMkdir("/path/directory");

This library have a lot of useful functions.

Solution 5 - Java

mkdir vs mkdirs


If you want to create a single directory use mkdir

new File("/path/directory").mkdir();

If you want to create a hierarchy of folder structure use mkdirs

 new File("/path/directory").mkdirs();

Solution 6 - Java

  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()
    

Source: this perfect tutorial , you find also an example of use.

Solution 7 - Java

For java 7 and up:

Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
    

It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:

> Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

> If this method fails, then it may do so after creating some, but not all, of the parent directories.

Solution 8 - Java

The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()

private void createUserDir(final String dirName) throws IOException {
    final File homeDir = new File(System.getProperty("user.home"));
    final File dir = new File(homeDir, dirName);
    if (!dir.exists() && !dir.mkdirs()) {
        throw new IOException("Unable to create " + dir.getAbsolutePath();
    }
}

Solution 9 - Java

Neat and clean:

import java.io.File;

public class RevCreateDirectory {

    public void revCreateDirectory() {
        //To create single directory/folder
        File file = new File("D:\\Directory1");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }
        //To create multiple directories/folders
        File files = new File("D:\\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!");
            }
        }

    }
}

Solution 10 - Java

Though this question has been answered. I would like to put something extra, i.e. if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.

public static void makeDir()
{
    File directory = new File(" dirname ");
    if (directory.exists() && directory.isFile())
    {
        System.out.println("The dir with name could not be" +
        " created as it is a normal file");
    }
    else
    {
        try
        {
            if (!directory.exists())
            {
                directory.mkdir();
            }
            String username = System.getProperty("user.name");
            String filename = " path/" + username + ".txt"; //extension if you need one

        }
        catch (IOException e)
        {
            System.out.println("prompt for error");
        }
    }
}

Solution 11 - Java

Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:

            File file = new File(filePath);
            if (file.getParentFile() != null) {
                file.getParentFile().mkdirs();
            }

Solution 12 - Java

This the way work for me do one single directory or more or them: need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */

    File filed = new File("C:\\dir1");
    if(!filed.exists()){  if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist");  }
    
    File filel = new File("C:\\dir1\\dir2");
    if(!filel.exists()){  if(filel.mkdir()){ System.out.println("directory is created");   }} else{ System.out.println("directory exist");  }
    
    File filet = new File("C:\\dir1\\dir2\\dir3");
    if(!filet.exists()){  if(filet.mkdir()){ System.out.println("directory is  created"); }}  else{ System.out.println("directory exist");  }
    

Solution 13 - Java

if you want to be sure its created then this:

final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
	final boolean logsDirExists = logsDir.exists();
	assertThat(logsDirExists).isTrue();
}

beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...

mkDir() returns only true if mkDir() creates it. If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.

assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.

Solution 14 - Java

This function allows you to create a directory on the user home directory.

private static void createDirectory(final String directoryName) {
	final File homeDirectory = new File(System.getProperty("user.home"));
	final File newDirectory = new File(homeDirectory, directoryName);
	if(!newDirectory.exists()) {
		boolean result = newDirectory.mkdir();

		if(result) {
			System.out.println("The directory is created !");
		}
	} else {
		System.out.println("The directory already exist");
	}
}

Solution 15 - Java

public class Test1 {
    public static void main(String[] args)
    {
       String path = System.getProperty("user.home");
       File dir=new File(path+"/new folder");
       if(dir.exists()){
           System.out.println("A folder with name 'new folder' is already exist in the path "+path);
       }else{
           dir.mkdir();
       }

    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjimmyView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavajmjView Answer on Stackoverflow
Solution 3 - JavaBenoit BlanchonView Answer on Stackoverflow
Solution 4 - JavaahvargasView Answer on Stackoverflow
Solution 5 - JavaBruceView Answer on Stackoverflow
Solution 6 - JavaMounaView Answer on Stackoverflow
Solution 7 - JavagrooView Answer on Stackoverflow
Solution 8 - JavaJon FreedmanView Answer on Stackoverflow
Solution 9 - JavaProgram-Me-RevView Answer on Stackoverflow
Solution 10 - JavascoreView Answer on Stackoverflow
Solution 11 - JavaMattView Answer on Stackoverflow
Solution 12 - JavaStefano CastagninoView Answer on Stackoverflow
Solution 13 - Javal0wacskaView Answer on Stackoverflow
Solution 14 - JavaBoubaView Answer on Stackoverflow
Solution 15 - JavaFathah Rehman PView Answer on Stackoverflow