Why doesn't File.renameTo (...) create destination subdirectories?

Why doesn't File.renameTo(...) create subdirectories contained in the path to the target file?


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 . For this to work, I have to ensure that all subdirectories exist either by creating them programmatically (i.e. mkdirs() ) or manually. Is there a reason why this feature was not included in this method?

+4
source share
4 answers

The current file API is not well implemented in Java. There are many features that would be desirable in a File API that is currently missing, such as moving, copying, and extracting file metadata.

I don’t think anyone can give you an answer on why the API is written as is. Probably a bad first project that went live and could not be changed due to backward compatibility issues.

These issues were addressed in the upcoming Java 7. An entirely new API was created for processing java.nio.file.Files files.

+1
source

Why?

Perhaps for consistency / compatibility with APIs that provide typical operating systems and other runtime libraries in a programming language.

Perhaps because it would be a bad idea to create intermediate directories if the user did not mean that this would happen; for example, if he / she simply hides one of the directory names in the path.

But this is not very relevant. The bottom line is that the renameTo method works this way.

+3
source

Subdirectories can be seen as an unexpected side effect from a different perspective. Are you sure everyone needs it implicitly?

+1
source

You have the answers, but I thought line by line: Request a function to add a new method File.renameTo (File src, File destination, int makeDirs)

with three constants for makeDirs: 1) do not create subfolders (folders) / dirs 2) just create a destination folder if it does not exist, if you specify / r 1 / 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) do your best sub dirs

  • if it has an OS that does not have subfolders, then do as it is now.
  • the old method will remain as
0
source

All Articles