2012-12-06 72 views
3

我希望能夠重命名文件夾列表以刪除不需要的字符(例如,點和雙倍空間必須成爲一個空格)。File.renameTo()沒有任何效果

一旦點擊了Gui中的一個按鈕,就會看到一個正確格式化名稱的消息框出現,表明格式設置正確並且函數被調用。 當我查看我創建的測試文件夾時,名稱不會更改(即使刷新後也不會更改)。使用硬編碼的字符串也不起作用。

我在忽略什麼?

public void cleanFormat() { 
    for (int i = 0; i < directories.size(); i++) { 
     File currentDirectory = directories.get(i); 
     for (File currentFile : currentDirectory.listFiles()) { 
      String formattedName = ""; 
      formattedName = currentFile.getName().replace(".", " "); 
      formattedName = formattedName.replace(" ", " "); 
      currentFile.renameTo(new File(formattedName)); 
      JOptionPane.showMessageDialog(null, formattedName); 
     } 
    } 
} 
+0

我認爲你需要刪除舊文件並創建新文件。 – kosa

+4

在[javadoc](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo%28java.io.File%29)中:*請注意,「文件'類定義了'move'方法移動或重命名一個平臺獨立的方式文件* – assylias

+0

我看着它在谷歌,我發現下面的代碼數次: '文件f =新的文件(」 Rename.java〜「); f.renameTo(新文件(「junk.dat」));' 除此之外沒有其他任何東西,你的意思是不贊成這樣做嗎? –

回答

7

對於未來的瀏覽器:這已修復Assylias的評論。下面你會找到修復它的最終代碼。

public void cleanFormat() { 
    for (int i = 0; i < directories.size(); i++) { 
     File currentDirectory = directories.get(i); 
     for (File currentFile : currentDirectory.listFiles()) { 
      String formattedName = ""; 
      formattedName = currentFile.getName().replace(".", " "); 
      formattedName = formattedName.replace(" ", " "); 
      Path source = currentFile.toPath(); 
      try { 
       Files.move(source, source.resolveSibling(formattedName)); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
+1

+1發佈您的解決方案;-) – assylias

0

那麼,首先File.renameTo正試圖重命名同一文件系統上的文件。

以下是java doc

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. 
0

所有檢查返回值首先,File.renameTo返回true,如果改名成功;否則爲假。例如。您無法在Windows上將文件從c:重命名/移動到d:。 最重要的是,改用Java 7的java.nio.file.Files.move。

0

對getName()的調用只返回文件的名稱而不返回任何目錄信息。所以你可能會試圖將文件重命名爲不同的目錄。

嘗試添加包含目錄給你傳遞到重命名

currentFile.renameTo(new File(currentDirectory, formattedName)); 

也像其他人所說的,你應該檢查renameTo的返回值可能是假的,或者使用文件的新方法的文件對象我發現它拋出了非常有用的IOExceptions類。