2012-08-03 65 views
1

我有這些文件:如何使用listIndexOf()刪除部分文件名?

Hingga Akhir Nanti - Allycats_part001 
, Hingga Akhir Nanti - Allycats_part002 
, Hingga Akhir Nanti - Allycats_part003 

我想以後刪除"_part001"與擴展.mp3文件夾中的所有文件取代它..

如何做到這一點在Java中的任何想法?

回答

2

你可以使用正則表達式myFileName.replaceAll("_part\\d+", ".mp3"),然後使用該文件的renameTo()方法來應用新名稱。

我相信它所需要的字符串是文件的完整路徑,所以要小心包括該文件(如果我在前面是正確的)。

3

我希望這段代碼能幫助你。

/** 
* Pass your file names here as a comma separated values 
* @param strs 
* @return nothing 
*/ 
public static void convertToMp3Extenesion(String... strs) { 
    for (String string : strs) { 
    File file = new File(string); 
    if (!file.exists()){ 
    continue; 
    } 
    String replacedFileName = string.replaceAll("_part\\d+", ".mp3"); 

    file.renameTo(new File(replacedFileName)); 
    } 

爲了從一個目錄把所有的文件,您可以增強上面的片段作爲,

/** 
* pass your directory containg your files 
* @param directory name 
* @return nothing 
*/ 
public static void convertToMp3Extenesion(String dir) { 

File fileDir = new File(dir); 
if (!fileDir.isDirectory()) { 
System.err.println(dir +" is not a valid directory "); 
return; 
} 

String[] strs = fileDir.list(); 
    //use if for debug. not so good, if files are too many 
//System.out.println("All Files "+Arrays.toString(strs)); 
for (String string : strs) { 

    File file = new File(dir+ File.separator+ string); 
    if (!file.exists()) { 
     continue; 
    } 
    String replacedFileName = string.replaceAll("_part\\d+", ".mp3"); 

    file.renameTo(new File(dir+ File.separator+ replacedFileName)); 
} 
+0

您好,感謝!它工作正常。但我想知道是否可以自動化代碼來讀取文件名而不是硬編碼呢? – user1573066 2012-08-03 04:33:19

+0

我已經編輯了這篇文章,只要你想。請嘗試使用它。 – sakthisundar 2012-08-03 04:53:12

+0

當我通過目錄'File dir = new File(「D:\\ Music \\ Assembled \\」);' – user1573066 2012-08-03 05:29:44