Reputation: 2321
Why doesn't File.renameTo(...)
create sub-directories contained in the destination file path?
For instance,
File source = new File(System.getProperty("user.dir") +
"/src/MyFolder/MyZipFolder.zip");
File dest = new File(System.getProperty("user.dir") +
"/src/MyOtherFolder/MyZipFolder.zip");
System.out.println(source.renameTo(dest));
Since MyOtherFolder
does not exist, this will always return false
. In order for this to work, I have to ensure that all sub-directories exist either by creating them programmatically(i.e. mkdirs()
), or manually. Is there a reason why this functionality was not included in this method?
Upvotes: 4
Views: 3856
Reputation: 1749
The current File API isn't very well implemented in Java. There is a lot of functionality that would be desirable in a File API that isn't currently present such as move, copy and retrieving file metadata.
I don't think anyone will be able to give you an answer as to why the API is written as is. Probably a poor first draft that went live and couldn't be changed due to backwards compatibility issues.
These issue have been addressed in the upcoming Java 7. A entirely new API has been created to deal with files java.nio.file.Files.
Upvotes: 1
Reputation: 36
You have answers but I was thinking along the lines: A feature request to add a new method File.renameTo(File src, File destination, int makeDirs)
with three constants for makeDirs: 1) do not make sub folder(s)/ dirs 2) only make the final folder if it does not exist meaning if you specify /r1/r2/r3/file.extn then only make r3 if it does not exist, if r2 or any other does not exist then return false. 3) make all possible sub dirs
Upvotes: 0
Reputation: 718906
Why?
Possibly for consistency / compatibility with the APIs that typical operating systems and other programming language runtime libraries provide.
Possibly because it would be a bad idea to create the intermediate directories if the user didn't really mean this to happen; e.g. if he / she simply mistyped one of the directory names in the path.
But it is not really relevant. The bottom line is that this is the way that the renameTo
method behaves.
Upvotes: 3
Reputation: 2415
Creating sub-directories may be considered as unexpected side effect from other point of view. Are you sure everyone needs it implicitly?
Upvotes: 1