批量修改同一格式文件的文件名:(这些文件名需要有规律)
- package com.kxg.file;
- import java.io.File;
- /*
- * 需求:把D:\Test\四大名著目下
- * 001_Hello_world_请修改我_西游记.txt
- * 002_Hello_world_请修改我_三国演义.txt
- * 003_Hello_world_请修改我_水浒传.txt
- * 004_Hello_world_请修改我_红楼梦.txt
- * 改为:
- * 001_西游记.txt
- * 002_三国演义.txt
- * 003_水浒传.txt
- * 004_红楼梦.txt
- */
- public class FileDemo9 {
- public static void main(String[] args) {
- // 封装目录
- File file = new File("D:\\Test\\四大名著\\");
- // 获取文件对象数组
- File[] arr = file.listFiles();
- // 遍历所有对象
- for (File f : arr) {
- // 获取每个文件的名字
- String name = f.getName();
- // 查找第一个_的索引,并从开始截取到次索引处获取前面的001,002,003,004
- int start = name.indexOf("_");
- String startName = name.substring(0, start);
- // 可以简化为 String start = name.substring(0, name.indexOf("_"));
- // 查找最后一个_的索引,并以这个索引为开始,截取到字符串末尾。得到_和四大名著名称。
- int end = name.lastIndexOf("_");
- String endName = name.substring(end);
- // 可以简化为 String end = name.substring(name.lastIndexOf("_"));
- // 把截取好的两个字符串拼接起来,就是需要改的文件名称。
- String newName = startName.concat(endName);
- // 把新的名称封装成File对象,千万不要忘记加上前面的目录。
- File newFile = new File(file, newName);
- // 给每个File对象重命名
- f.renameTo(newFile);
- System.out.println(f.getName());
- }
- }
- }
复制代码
|