Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is mkdir () in Java?

The mkdir() method is a part of File class. The mkdir() function is used to create a new directory denoted by the abstract pathname. The function returns true if directory is created else returns false. Function Signature: public boolean mkdir() Syntax: file.mkdir()

Does mkdir overwrite existing directory in Java?

mkdir -p WILL NOT give you an error if the directory already exists. Also, the directory will remain untouched i.e. the contents are preserved as they were.

Why is mkdir return false?

It returns false if the directory already exists or if there was an error creating the directory. Now there's a piece of useful API. In Android API 26 or above required!

What is the return type of the method MKD are in the class Java IO file?

Return Value: The function returns boolean data type.


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

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

Example:

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

will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir


mkdirs() will create the specified directory path in its entirety where mkdir() will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.

In other words mkdir() is like mkdir and mkdirs() is like mkdir -p.

For example, imagine we have an empty /tmp directory. The following code

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

would create the following directories:

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

Where this code:

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

would not create any directories - as it wouldn't find /tmp/one/two - and would return false.


mkdir()

creates only one directory at a time, if it is parent that one only. other wise it can create the sub directory(if the specified path is existed only) and do not create any directories in between any two directories. so it can not create smultiple directories in one directory

mkdirs()

create the multiple directories(in between two directories also) at a time.