Java如何将文件下的所有文件进行批量更改和替换

Java如何将文件下的所有文件进行批量更改和替换

  1. 将F盘下tmp文件夹下的文件循环取出
  2. 进行文件的替换(这里将李替换成1
  3. 修改完成写入到文件夹中
public class Test {

    public static void main(String[] args) throws IOException {
        List fileStr =  Files.walk(Paths.get("F:\\tmp"))
                .filter(Files::isRegularFile)
                .collect(Collectors.toList());
        String target = "李";
        String replacement = "1";
        fileStr.forEach(x->modify( x.toString(), target, replacement));
    }
    public static void modify(String path, String target, String replacement) {
        File file = new File(path);
        if (file.exists()) {
            modifyFileContent(file, target, replacement);
        } else {
            System.out.println("文件不存在"+ path);
        }
    }
    /**
     * 修改文件中的内容
     * @param file 文件
     * @param target 被替换的字符串
     * @param replacement 替换字符串
     */
    public static void modifyFileContent(File file, String target, String replacement) {
        System.out.println("开始修改文件:+file.getName(), 替换 "+target+"为"+replacement);
        StringBuilder sb = new StringBuilder();
        //修改的行数
        int cnt = 0;
        //替换所在的行
        int rowLine = 0;
        //换行符
        String enter = System.getProperty("line.separator");
        PrintWriter pw = null;
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            for (line = br.readLine(); line != null; line = br.readLine()) {
                rowLine++;
                if (line.contains(target)) {
                    line = line.replace(target, replacement);
                    System.out.println("替换所在行:"+rowLine);
                    cnt++;
                }
                //数据暂存在 StringBuilder 中
                if (rowLine == 1) {
                    sb.append(line);
                } else {
                    sb.append(enter).append(line);
                }
            }
            pw = new PrintWriter(new FileWriter(file));
            pw.print(sb);
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在!"+ e);
            System.exit(1);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值