2011-09-06 117 views
17
File oldFile = new File("old"); 
if (oldFile.renameTo(new File("new"))){ 
    System.out.println(oldFile.getName());//this prints "old" 
} 

我看過的OpenJDK源,並有renameTo(文件DEST)函數如下所示:爲什麼File.renameTo不會更改文件指向的位置?

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 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" 
} 
+0

你在上一個例子中正確地做了。 – Marcelo

+0

文件是路徑的不可變名稱。它不一定存在,它不會改變。 –

回答

12

最簡單的可能的解釋是,to quote the Javadoc

File類的實例是不可變的;即一旦創建,由File對象表示的抽象路徑名將永遠不會改變。

正如其他人所說,這裏沒有對或錯。但是,只要圖書館的設計人員做出上述選擇,目前的行爲renameTo成爲唯一可能的行爲。

至於你的第二個代碼片段,我可以看到它沒有任何缺陷。

4

一個文件對象只是一個名稱,它甚至不必存在。 renameTo API調用實際上重命名文件系統上的文件,但不會更改文件對象,因爲這是API設計的目的。這裏沒有對或錯。 Sun的API設計人員認爲這樣做更有意義。

+0

我相信我曾經在Sun聽過有人討論過他們應該如何命名類路徑而不是文件來更好地闡明這一點...... –

1

從快速瀏覽到File,它看起來像它的不可變的。它有一些setter,但它們在文件系統上的實際文件上運行,而不是在File實例上運行。

所以重命名不修改當前實例保持相同的風格。

相關問題