2012-08-03 40 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