Difference between mkdir () and mkdirs () in java for java.io.File

Can someone tell me the difference between file.mkDir() and file.mkDirs() ?

+80
java directory
Mar 22 2018-12-22T00:
source share
3 answers

mkdirs() also creates parent directories in the path that this File represents.

javadocs for mkdirs() :

Creates a directory with the name of this abstract path, including any necessary but non-existent parent directories. Note that if this fails to execute some of the required parent directories.

javadocs for mkdir() :

Creates a directory with the name of this abstract path.

Example:

 File f = new File("non_existing_dir/someDir"); System.out.println(f.mkdir()); System.out.println(f.mkdirs()); 

will give false for the first [and no directory will be created], and true for the second, and you created non_existing_dir/someDir

+111
Mar 22 2018-12-22T00:
source share

mkdirs() will create the specified directory path completely, where mkdir() will only create the lowest directory if it cannot find the parent directory of the directory it is trying to create.

In other words, mkdir() is similar to mkdir , and mkdirs() is similar to mkdir -p .

For example, imagine that we have an empty /tmp . Following code

 new File("/tmp/one/two/three").mkdirs(); 

will create the following directories:

  • /tmp/one
  • /tmp/one/two
  • /tmp/one/two/three

Where is this code:

 new File("/tmp/one/two/three").mkdir(); 

would not create any directories - since it would not find /tmp/one/two - and return false .

+39
Mar 22 2018-12-22T00:
source share
 mkdir() 

creates only one directory at a time if it is only a parent. In another way, it can create a subdirectory (if the specified path exists only) and not create directories between any two directories. therefore, it cannot create smultiple directories in the same directory

 mkdirs() 

Create multiple directories (simultaneously between two directories).

+3
Jun 20 '13 at 11:45
source share



All Articles