文件夹下内容批量重命名

实现文件夹下所有内容重命名

最近在网上下载了个项目练练手,发现文件名都是被重命名过的,每个文件都加上了广告语,就想着批量修改一下,以下代码来源网络,我自己稍微做了一下修改,用于重命名文件夹下的所有内容。

代码

import java.util.*;
import java.io.*;
/**
 * 文件夹下所有内容批量重命名(替换字符)
 *
 * @author kai_qian
 * @version v1.0
 * @since 2020/03/10 09:30
 */
public class FileRename{
    public static void main(String[] args)throws IOException{
        String fileStr="";
        String rStr="";
        String newStr="";
        try{
            System.out.print("\n输入文件夹路径:");
            Scanner fsc = new Scanner(System.in);
            fileStr = fsc.nextLine();
            System.out.print("\n输入被替换字符:");
            Scanner rsc = new Scanner(System.in);
            rStr = rsc.nextLine();
            System.out.print("\n输入替换字符:");
            Scanner newsc = new Scanner(System.in);
            newStr = newsc.nextLine();
        }catch(Exception e){
            System.out.println("Error: 001--"+e.getMessage());
        }
        RenameFile(fileStr,rStr,newStr);
    }

    /**
     * 将文件路径下的所内容重命名
     *
     * @param filepath 文件夹路径
     * @param rStr 要被替换的字符串
     * @param newStr 用于替换的字符串
     * @return
     * @throws IOException
     */
    public static boolean RenameFile(String filepath,String rStr,String newStr) throws IOException{
        try {
            File fileDir = new File(filepath);
            for (File file : fileDir.listFiles())
            {
                String fileName = file.getName();
                String newName = fileName.replace(rStr, newStr);
                File f_new = new File(filepath, newName);
                file.renameTo(f_new);
                System.out.println(filepath + "\\" + fileName + ">>" + filepath + "\\" + newName + "-----" + f_new.exists());
                if (!file.isFile()) {
                    // 递归修改,使用新的文件名作为路径
                    RenameFile(filepath+"\\"+newName, rStr, newStr);
                }
            }
        }catch(Exception e){
            System.out.println("错误信息: " + e.getMessage()+"   请确认文件夹是否存在!");
        }
        return true;
    }
}

说明

  1. 输入对应文件夹(会修改这个文件夹下所有内容)
  2. 再输入文件名称中要替换的字符
  3. 再输入要替换成的新字符(想替换为空可以直接回车)

类似的其他功能可以根据上面的代码做适当的调整。

posted @ 2020-03-10 09:59  它山之玉  阅读(613)  评论(0编辑  收藏  举报