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?
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.
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.
If the directory already exists, then it can't be "created", therefore the method returns false as per the docs.
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With