Java实现文件批量重命名

使用了File类(文件管理)和Pattern类(正则匹配)。

对原文件名正则匹配

新文件名带序号

 1 import java.io.File;
 2 import java.io.FilenameFilter;
 3 import java.util.regex.Pattern;
 4 
 5 public class Rename
 6 {
 7     public static String URL="D:\\mb\\2\\";
 8     //the dir of files
 9     public static String nameRule="2.*";
10     //the rule for finding files
11     public static String reNameRule="2.part#.r-a-r";
12     //# represent the new name index of files in [1,n], n is the num of old files, by asc order
13     public static  void main(String []args)
14     {
15         File file=new File(URL);
16         File []files=file.listFiles(new FilenameFilter() {
17             @Override
18             public boolean accept(File dir, String name) {
19                 return Pattern.matches(nameRule,name);
20             }
21         });
22         System.out.println("There are "+files.length+"(s) files found!");
23         System.out.println("Rename Begin!");
24         String []s=reNameRule.split("#");
25 
26         for(int i=0;i<files.length;i++)
27         {
28             File newf=new File(URL+s[0]+(i+1)+s[1]);
29             files[i].renameTo(newf);
30         }
31         System.out.println("Rename Complete!");
32     }
33 }

测试文件:

运行结果:

posted @ 2018-01-23 18:20  我也想学编程  阅读(369)  评论(0编辑  收藏  举报