JDK-1241581 : mkdir returns false if directory already exists, so mkdirs has strange behavior
  • Type: Bug
  • Component: hotspot
  • Sub-Component: runtime
  • Affected Version: 1.0
  • Priority: P5
  • Status: Closed
  • Resolution: Not an Issue
  • OS: solaris_1
  • CPU: sparc
  • Submitted: 1996-03-11
  • Updated: 1996-05-07
  • Resolved: 1996-05-07
Description
In class java.io.File, the mikdir method seems to return false if
the directory in questions already exists.  This has two bad
properties:

(1) It is actually difficult to tell, after a call to mkdir, whether the
directory exists, which is usually of greater interest than whether
the transition from nonexistent to existent occurred.

(2) As evidence of this, the value returned by mkdirs is almost
useless.  You actually expect one of the parent directories to exist;
so mkdirs almost always returns false.  If mkdir were to return true
iff the directory exists after the call to mkdir, then mkdirs would return
true iff the directory (and all its parents) exist after the call to mkdirs.

Comments
EVALUATION This seems a reasonable complaint, but it is an API change.
11-06-2004

SUGGESTED FIX Change mkdir to return true if the directory already exists.
11-06-2004

PUBLIC COMMENTS mkdir returns false if directory already exists, so mkdirs has strange behavior --------------BEGIN SUMMARY-------------- For all of the operations in the File class that return a boolean, the general rule is that the method should return true if the operation *really* happened ("Was a file really deleted?" "Was a file really renamed?" "Was a directory really created?") If we changed File.mkdir() to return true if the directory already existed, then the boolean returned no longer indicates "did the operation *really* just happen?" but instead indicates "does the state of things now reflect the change I was asking for?" If we wanted consistency across the API (which we do) we'd have to change, for example, File.delete() to return true if the file never existed in the first place OR if it was really deleted. That's asking for more confusion. So in summary: File.mkdir() will return false if the target exists. File.mkdirs() will return false if any directory in the path was not created (e.g., it already existed) which will usually be the case. But a programmer has the facilities to see if a directory exists (File.exists()) which yes, probably will be of more interest in most cases. What's been changed in 1.1 is that mkdirs() will not try to recursively make the parent if the parent already exists. This eliminates the problem that generated the SecurityException in the case where the target already exists (in bug 1229211). In general, its probably best to check if the target exists before creating it: File dir = new File("/usr/include"); if(!dir.exists()) dir.mkdirs(); // make path only if it doesn't exist
10-06-2004