Java的File.renameTo()有问题,特别是在Windows上,似乎。
正如
API documentation所说,
Many aspects of the behavior of this
method are inherently
platform-dependent: The rename
operation might not be able to move a
file from one filesystem to another,
it might not be atomic, and it might
not succeed if a file with the
destination abstract pathname already
exists. The return value should always
be checked to make sure that the
rename operation was successful.
在我的情况下,作为升级过程的一部分,我需要移动(重命名)可能包含千兆字节数据的目录(大量的子目录和不同大小的文件)。移动总是在同一个分区/驱动器内完成,所以实际上不需要物理移动磁盘上的所有文件。
应该没有任何文件锁到要移动的目录的内容,但是,很多时候,renameTo()无法完成其任务并返回false。 (我只是猜到,可能一些文件锁在Windows上有点任意地过期。)
目前我有一个后备方法,使用复制&删除,但这很糟糕,因为它可能需要很多时间,这取决于文件夹的大小。我也考虑简单地记录一个事实,用户可以手动移动文件夹,以避免等待时间,潜在的。但正确的方式显然是自动和快速。
所以我的问题是,你知道一个替代,可靠的方法做快速移动/重命名与Java在Windows上,使用纯JDK或一些外部库。或者,如果你知道一个简单的方法来检测和释放给定文件夹及其所有内容(可能是数千个单独文件)的任何文件锁,这也很好。
编辑:在这种特殊情况下,似乎我们只使用renameTo()通过考虑更多的事情了;见this answer。