Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.mkdir or mkdirs return false - Reason?

Why file.mkdir is returning false?

Google indicates that there could be several reasons (e.g. security, permissions, pathname, etc).

My questions:

  1. How to find the exact reason of returning false?
  2. If security/permissions is a reason, then why is SecurityException not thrown?
like image 562
Sandeep Jindal Avatar asked Aug 30 '12 17:08

Sandeep Jindal


People also ask

What is difference between mkdir and Mkdirs?

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 .

What is the return type of mkdir?

RETURN VALUEUpon successful completion, mkdir() shall return 0. Otherwise, -1 shall be returned, no directory shall be created, and errno shall be set to indicate the error.

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.


2 Answers

mkdir and mkdirs return false if the directory already exists, so that might be one reason for the failure.

If you are using Java 7, you can use the Files class. It throws an IOException on error with pretty good descriptions.

Files.createDirectory(file.toPath()); 
like image 99
Michael Krussel Avatar answered Sep 19 '22 20:09

Michael Krussel


If security/permissions is a reason, then why is SecurityException NOT thrown (which is mentioned in javadoc)?

A SecurityException is thrown when you don't have JVM-level permission to do something, not OS-level

Is there a way to find the exact reason why of returning false?

No, AFAIK. The only way to know would be to check the permissions on the directory yourself, make sure it doesn't exist before calling them, check if the parent directory exists, etc.

However, if you're using Java 7 or higher, you can use NIO instead to create the directory. Specifically, Files.createDirectory:

File dir = new File("mydir"); Files.createDirectory(dir.toPath()); 

If you want to use NIO entirely without using java.io.File, you can use Paths.get to create a Path instead:

Path dir = Paths.get("mydir"); Files.createDirectory(dir); 

In both cases, if the directory can't be created, it will throw an IOException with an exact reason for why the operation failed.

This is true for most of the methods in Files, and so using it is recommended over using the methods in the File class.

like image 36
Brian Avatar answered Sep 21 '22 20:09

Brian