【问题标题】:Why File.renameTo doesn't change where File points to?为什么 File.renameTo 不会改变 File 指向的位置?
【发布时间】:2011-09-06 13:08:41
【问题描述】:
File oldFile = new File("old");
if (oldFile.renameTo(new File("new"))){
    System.out.println(oldFile.getName());//this prints "old"
}

我查看了 openJDK 源码,renameTo(File dest) 函数看起来像这样:

public class File implements Serializable, Comparable<File> {
    static private FileSystem fs = FileSystem.getFileSystem();
    private String path;
    ...
    public boolean renameTo(File dest) {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(path);
            security.checkWrite(dest.path);
        }
        return fs.rename(this, dest);
    }
    ...
}

所以路径变量永远不会改变。为什么呢?使用重命名的 File 变量的正确方法是什么?目前我这样做:

File oldFile = new File("/home/blin/misk/old");
File newFile = new File("/home/blin/misk/new");
if (oldFile.renameTo(newFile)){
    oldFile=newFile;
    System.out.println(oldFile.getName());//this prints "new"
}

【问题讨论】:

  • 您在上一个示例中做得正确。
  • 文件是路径的不可变名称。它不必存在,也不会改变。

标签: java io


【解决方案1】:

最简单的解释是,to quote the Javadoc:

File 类的实例是不可变的;也就是说,一旦创建,File 对象所代表的抽象路径名就永远不会改变。

正如其他人所说,这里没有对错。然而,一旦库的设计者做出上述选择,renameTo 的当前行为就成为唯一可能的行为。

至于您的第二个代码 sn-p,我看不出它有任何缺陷。

【讨论】:

    【解决方案2】:

    File 对象只是一个名称,它甚至不必存在。 renameTo API 调用实际上重命名文件系统上的文件,但不会更改文件对象,因为这是 API 的设计目的。这里没有对错。 Sun 的 API 设计人员认为这样更有意义。

    【讨论】:

    • 我相信我曾经听过 Sun 的某个人讨论他们应该如何将类命名为 Path 而不是 File 以更好地澄清这一点......
    【解决方案3】:

    快速浏览一下 File,它看起来是不可变的。它有一些设置器,但它们在文件系统上的实际文件上操作,而不是在 File 实例上。

    所以重命名不修改当前实例保持相同的样式。

    【讨论】:

      猜你喜欢
      • 2013-08-24
      • 2017-06-24
      • 2020-12-01
      • 2012-07-25
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多