Java 修改文件中的内容

所谓修改内容,其实就是全局替换文件中的某个字符串,很简单的操作。

      public static void startModify(String path, String target, String replacement) {
        File file = new File(path);
        if (file.exists()) {
            modifyFileContent(file, target, replacement);
        } else {
            LOGGER.error("文件 {} 不存在", path);
        }
    }
   /**
     * 修改文件中的内容
     * @param file 文件
     * @param target 被替换的字符串
     * @param replacement 替换字符串
     */
    public static void modifyFileContent(File file, String target, String replacement) {
        LOGGER.info("开始修改文件:{}, 替换 {} 为 {}", file.getName(), target, replacement);
        StringBuilder sb = new StringBuilder();
        //记录修改的行数
        int cnt = 0;
        //记录替换所在的行
        int rowLine = 0;
        //换行符
        String enter = System.getProperty("line.separator");
        
        //printWriter原本也想放在 try-with 中,少写点代码,
        //但是一个文件不能同时读写,pw 和 br 对同一个文件操作的结果时,文件的内容被清空!!!
        //不妨试下,将 pw 申明在 try-with 中,看下运行结果。
        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);
                    LOGGER.info("替换所在行:{}", 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) {
            LOGGER.error("文件不存在!", e);
            System.exit(1);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
        LOGGER.info("修改文件:{} 结束,一共替换{}行数据", file.getName(), cnt);
    }

PS: 在Windows 开发时修改.sh文件后,到linux机器上查看该文件,会发现修改的地方多了\r\r。比如修改“/path/AService”为“/path/BController”,在Linux上就变成了“/path/BController\r\r”。

  • 8
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值