使用java对文件批量改名

Posted on 2017-09-28 16:18  想念熊  阅读(855)  评论(0)    收藏  举报

1:文件路径已修改前文件名

1 E:\改名\文本

2:java代码改文件名

 1 public class ChangeName {
 2     public static void main(String[] args) {
 3         updateFileNames("E:\\改名\\文本");
 4     }
 5     public static void updateFileNames(String url) {
 6         //获取文件所在目录
 7         File file = new File(url);
 8         // 获取文件夹绝对路径
 9         String path = file.getAbsolutePath();
10         // 判断文件目录是否存在,且是文件目录,非文件
11         if (file.exists() && file.isDirectory()) {
12             // 遍历文件夹下的所有文件
13             File[] childFiles = file.listFiles();
14             for (int i = 0; i < childFiles.length; i++) {
15                 File file2 = childFiles[i];
16                 if (file2.isFile()) {
17                     String oldName = file2.getName();
18                     String newName="文件"+i+".txt";
19                     oldName.replace(oldName, newName);
20                     file2.renameTo(new File(path + "\\" + newName));
21                 }
22             }
23         }
24     }
25 }

3:修改后的文件名