2015-02-10 94 views
0

我有圖像目錄,我想通過刪除名稱中的所有空格來重命名文件。從目錄中的所有文件名刪除空格 - Java

假設我有一個名爲「f il ena me .png」的文件名(我計劃檢查目錄中的所有文件名)。如何刪除所有空格並重命名圖像,以便正確的文件名(對於此特定情況)是「文件名.png」。

到目前爲止,我已經嘗試了下面的代碼,它實際上刪除了目錄中的圖像(我正在目錄中的一個圖像上測試它)。

public static void removeWhiteSpace (File IBFolder) { 
    // For clarification: 
    // File IBFolder = new File("path/containing/images/folder/here"); 
    String oldName; 
    String newName; 
    String temp; 
    for (File old : IBFolder.listFiles()) { 
     oldName = old.getName(); 
     temp = oldName.replaceAll(" ", ""); 
     // I have also tried: 
     // temp = oldName.replaceAll("//s", ""); 
     temp = temp.split(".png")[0]; 
     newName = temp + ".png"; 
     System.out.println(newName); 
     old.renameTo(new File(newName)); 
    } 
} 
+0

請不要讓變量名以大寫字母開頭 - 它違背JAVA命名約定。 – Alexander 2015-02-10 23:51:47

+0

它的打印文件名是否正確? – 2015-02-11 00:00:14

回答

2

我認爲它不會刪除的圖像,但它們移動到您當前的工作目錄,並將其重命名爲newName,但由於newName缺少路徑信息時,將重命名/移動到」 ./ 「(無論你在哪裏運行你的程序)。

我認爲你必須在這些線路中的錯誤: 「」

temp = temp.split(".png")[0]; 
    newName = temp + ".png"; 

是一個wilcard字符,可以說你的文件被稱爲「some png.png」,newName將是「som.png」,因爲「some png.png」.replaceAll(「」,「」).split(「.png」 )導致「som」。

如果由於某種原因,你需要的String.split()方法,請適當引用「」:

temp = temp.split("\\.png")[0]; 
+0

嘿!你是對的。我一直沒有注意到我正在工作的當前目錄。哎呀!謝謝您的幫助。我會鼓勵它,並確保我給它的路徑名稱。我理解你對於大寫字母變量名稱的觀點,因爲IB代表着某些東西,所以我有點撕碎它將它重命名爲小寫字母。我可能會重寫一次完成的程序,並替換更有意義的var名稱。 – tbcrawford 2015-02-10 23:59:06

+0

什麼是「temp.split(」。png「)? – Alexander 2015-02-11 00:05:19

+0

你是對的,我得到了我的解決方案,我會在一分鐘後將它作爲我的問題的答案張貼,再次感謝您的幫助。忘了我在發佈之前發現了一個bug – tbcrawford 2015-02-11 00:06:44

1

忽略命名約定(我打算以後再修改)這裏我敲定了解決方案。

public static void removeWhiteSpace (File IBFolder) { 
    // For clarification: 
    // File IBFolder = new File("path/containing/images/folder/here"); 
    String oldName; 
    String newName; 
    for (File old : IBFolder.listFiles()) { 
     oldName = old.getName(); 
     if (!oldName.contains(" ")) continue; 
     newName = oldName.replaceAll("\\s", ""); 

     // or the following code should work, not sure which is more efficient 
     // newName = oldName.replaceAll(" ", ""); 

     old.renameTo(new File(IBFolder + "/" + newName)); 
    } 
} 
+0

你還是忘了逃避「。」 - 它應該是.split(「\\。png」)! – Alexander 2015-02-11 00:12:26

+0

明白了!非常抱歉,代碼錯誤。在5天前進入Java我相信我已經習慣了一些小的東西,我很感激這個幫助,我發現它不必像上面提到的那樣泄漏它,但是我確實需要知道 .split( 「\\。png」) 您在我的程序中提到了另一點。 – tbcrawford 2015-02-11 00:16:23

相關問題