474

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.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
jimmy
  • 8,121
  • 11
  • 36
  • 40
  • 31
    please review your selection of the correct answer. The solution proposed by JigarJoshi is misleading. It doesn't address the problem correctly (see my comment). The (simple) solution proposed by Bozho is much better. – mwhs Nov 24 '13 at 11:36
  • `mkdir` is idempotent in java. The implementation will do the check if the directory exists for you, and only create it if it does not exist. – mwhs Jul 21 '15 at 12:51

16 Answers16

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

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Thanks and if i want to give name to that directory, is this possible – jimmy Sep 03 '10 at 10:32
  • 37
    Much better answer than the one selected as the correct one by the OP. Checking for existence of the directory before creating it should become a well-known anti-pattern. – mwhs Nov 24 '13 at 11:30
  • 8
    what if the directory is already exists? It would do overwriting? or skip the process. – Avinash Raj Oct 08 '15 at 05:34
  • 3
    @AvinashRaj please check http://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdirs() – Tascalator Oct 22 '15 at 01:12
  • 1
    @Tascalator it's not clear from documentation can you elaborate? Also answer should be complemented with answer to `what if the directory is already exists? It would do overwriting? or skip the process.` question. – mrgloom Jun 01 '17 at 09:28
  • 7
    it is clear: `Returns: true if and only if the directory was created, along with all necessary parent directories; false otherwise` – xeruf Jun 11 '17 at 15:29
  • 3
    It won't overwrite an existing directory. It will return false. – DarkHark Oct 30 '18 at 18:20
558

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();
}
paradocslover
  • 2,932
  • 3
  • 18
  • 44
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 275
    -1: That is actually a **really bad** technique to create a directory. The access to the FS is not reserved to a dedicated resource. Between `if(!theDir.exists())` and `theDir.mkdir()` the status could have changed, as well as it could change in between **not** creating the directory (because of `exists` returning `true`) and needing it. The result of the method `exists` should never be used to decide wether to create a directory or not. Just call `mkdir`, no exception will be thrown if it already exists. – mwhs Nov 24 '13 at 11:26
  • 5
    @mwhs I understand that it's better to not check for the directory but I don't understand your justification (second part). Can't the status change between calling `mkdir` and needing the directory as well? I assume you meant that some other process deletes the directory. – Episodex Jul 17 '15 at 12:54
  • 2
    @Episodex Directories are shared resources. Just don't use the above solution, it is wrong for different reasons. Unclear how the PO could have thought this is the correct answer. If you want assertions about IO resources you need to use locks, not booleans. – mwhs Jul 20 '15 at 09:27
  • 53
    @mhws I know this post is a couple months old but if you look at the `mkdirs` implementation, from the source code, the very first thing that gets called is `if (exists()) { return false; }`. The implementation itself checks first to see if the directory already exists so the only thing this answer is at fault for, perhaps, is checking that condition 2x. Not near as bad as you're making it out to be. – Michael Hogenson Nov 12 '15 at 20:59
  • 6
    As of Java 7, you should probably use the methods in `Files` as in the more recent answer by Benoit Blanchon. (This answer appears to have been written before Java 7.) – Brick Sep 08 '16 at 16:58
  • 1
    Why no `theDir.close();` ? – Gank Sep 10 '16 at 03:26
  • @Gank see http://stackoverflow.com/questions/4752266/why-java-io-file-doesnt-have-a-close-method – user812786 Sep 12 '16 at 16:52
  • the one-liner answer at the bottom is better – john k Feb 26 '18 at 19:47
  • @MichaelHogenson The operation of checking for existence of dir and creation if doesn't exists should be a single process and atomic. java.nio does it atomically, check createDirectories method in class Files. mwhs was absolutely correct. – Praveen Tiwari Mar 07 '19 at 18:54
  • 1
    @p_champ Of course java.nio is better. Either way my point is moot because they changed the implementation, which is expected. At the time of writing though, best practices aside, the code would check to see if a directory exits, and if it was determined that it did, `mkdir()` would have checked again. If it had been deleted in the extremely brief period between the two calls, no harm, since `mkdir()` would simply return `false`. The biggest flaw in the code, in my opinion, is that `true` is hard coded as a return value rather than the value returned by the `mkdir()` method call. – Michael Hogenson Aug 15 '19 at 16:35
195

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

For instance:

Files.createDirectories(Paths.get("/path/to/directory"));
Benoit Blanchon
  • 13,364
  • 4
  • 73
  • 81
38

You can try FileUtils#forceMkdir

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

This library have a lot of useful functions.

Suzana
  • 4,251
  • 2
  • 28
  • 52
ahvargas
  • 903
  • 10
  • 17
  • 1
    Much better than pure mkdirs: handles concurrency, checks if the operation succeeded, checks if the directory (not a file!) exists. – Andrey May 06 '15 at 11:26
  • 1
    Where does it say it handles concurrency? I actually tried to find it before I read this, looking for a way to let several threads manipulate filesystem without messing up. – brat Mar 01 '21 at 12:15
  • Use the [source](https://commons.apache.org/proper/commons-io/javadocs/api-2.5/src-html/org/apache/commons/io/FileUtils.html#line.2455) Luke – ahvargas Oct 19 '21 at 16:19
32

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();
Bruce
  • 8,609
  • 8
  • 54
  • 83
25
  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.

Mouna
  • 3,221
  • 3
  • 27
  • 38
24

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.

groo
  • 4,213
  • 6
  • 45
  • 69
8

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();
    }
}
Jon Freedman
  • 9,469
  • 4
  • 39
  • 58
  • 3
    As mentioned in the comment by @mwhs on Jigar Joshi's answer, checking for existence first is not only not necessary but actually a bad idea. – Bdoserror Nov 25 '14 at 20:56
5

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

    }
}
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
Program-Me-Rev
  • 6,184
  • 18
  • 58
  • 142
3

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");
        }
    }
}
bdean20
  • 822
  • 8
  • 14
score
  • 521
  • 1
  • 8
  • 22
  • 4
    As mentioned in the comment by @mwhs on Jigar Joshi's answer, checking for existence first is not only not necessary but actually a bad idea. – Bdoserror Nov 25 '14 at 20:57
3

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();
            }
Matt
  • 688
  • 5
  • 12
1

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

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.

Virb
  • 1,639
  • 1
  • 16
  • 25
l0wacska
  • 31
  • 4
0

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");
    }
}
Bacara
  • 6,903
  • 1
  • 20
  • 21
  • As mentioned in the comment by @mwhs on Jigar Joshi's answer, checking for existence first is not only not necessary but actually a bad idea. – Bdoserror Nov 25 '14 at 20:58
0

You can use the Short Circuit OR feature in an 'if' statement. This feature allows you to check if a directory exists and create it in a single line of code, as shown in this example:

public File checkAndMakeTheDirectory() {
  File theDirectory = new File("/path/directory");
  if (theDirectory.exists() || theDirectory.mkdirs())
    System.out.println("The folder has been created or already exists");
  return theDirectory;
}

The 'if' statement in Java has a useful feature known as Short Circuit Evaluation. If the first part of the 'if' statement is true, then the second part will not be evaluated. Conversely, if the first part is false, then the second part will still be evaluated.

Farzan.s
  • 945
  • 8
  • 9
-2
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();
       }

    }
}
Fathah Rehman P
  • 8,401
  • 4
  • 40
  • 42
  • As mentioned in the comment by @mwhs on Jigar Joshi's answer, checking for existence first is not only not necessary but actually a bad idea. – Bdoserror Nov 25 '14 at 20:57