开发者

Renaming a file without using renameTo() - Java

Disregarding my last post, I've found the source of the problem. I'm using

a.renameTo(b)

when b doesn't exist. The re开发者_运维知识库ason it doesn't exist is because there is a symbolic link so if b is /usr/name/folder/file, then b really is /mnt/MountTest because the symlink is to that directory.

So the question is, is there an alternative way to rename a file in Java using a string value? If not, how can this rename procedure be done differently?


A rename would rename it... if it were on the same filesystem.

If a renameTo() fails, you'll need to copy it to the new location, then delete the original.


Renaming files is also highly problematic accross file systems. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4073756. Commenters of the bug report posted some sample code and also pointed out that you can use Process.exec. Both Apache Commons IO and and Google Guava have utilities for safely moving files as well:

  • http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#move(java.io.File,%20java.io.File)
  • https://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/FileUtils.html#moveFile(java.io.File,%20java.io.File)


I think you are confusing things. A java.util.File doesn't represent a file on some filesystem. It represents a path to a file.


The problem is not that a symlink is involved; the problem is that you can't atomically rename across filesystems. The meta-problem is that the Java File operations are badly designed, and don't throw proper exceptions, and provide no error codes when something fails!


How about:

a.renameTo(new File("/your/path/here/");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜