Why doesn't File.renameTo(…) create sub-directories of destination?

落爺英雄遲暮 提交于 2019-12-23 12:35:08

问题


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?


回答1:


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.




回答2:


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.




回答3:


Creating sub-directories may be considered as unexpected side effect from other point of view. Are you sure everyone needs it implicitly?




回答4:


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

  • if its a OS that does not have sub folders then do as you do now
  • the old method would remain as is


来源:https://stackoverflow.com/questions/6817142/why-doesnt-file-renameto-create-sub-directories-of-destination

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!