Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mkdirs() return value for already existing directories

Tags:

java

file

mkdirs

File.mkdirs JavaDocs:

public boolean 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.

Returns: true if and only if the directory was created, along with all necessary parent directories; false otherwise

My question is: Does mkdirs() return false if some of the directories it wanted to create already existed? Or does it just return true if it was successful in creating the entire path for the File, whether or not some directories already existed?

like image 344
Davio Avatar asked Nov 27 '14 11:11

Davio


People also ask

Does mkdir overwrite existing directories?

1 Answer. Show activity on this post. The mkdir command will create any folders that do not exist in the specified path, unless extensions are disabled ( setLocal enableExtensions ) - regardless, it will not destroy a directory and create a new one with the same name.

What is the use of mkdir () and Mkdirs () methods?

The mkdirs() method is a part of File class. The mkdirs() function is used to create a new directory denoted by the abstract pathname and also all the non existent parent directories of the abstract pathname. If the mkdirs() function fails to create some directory it might have created some of its parent directories.

What does mkdir do if directory already exists Java?

If the directory already exists, then it can't be "created", therefore the method returns false as per the docs.

How do you create a directory if it does not exist in Java?

You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.


1 Answers

It returns false.

From java doc: - true if the directory was created, false on failure or if the directory already existed.

You should do something like this:

if (file.mkdirs()) {
    System.out.format("Directory %s has been created.", file.getAbsolutePath());

} else if (file.isDirectory()) {
    System.out.format("Directory %s has already been created.", file.getAbsolutePath());

} else {
    System.out.format("Directory %s could not be created.", file.getAbsolutePath());
}
like image 66
chrizdekok Avatar answered Oct 25 '22 08:10

chrizdekok