java程序指定替换或删除文件中的行或字符串

文件内容指定替换与删除

原数据量
在这里插入图片描述

在这里插入图片描述需要去除的内容
在这里插入图片描述需要替换的内容
在这里插入图片描述
正式表lnk_scan_real_time_stock
临时表 lnk_scan_real_time_stock_temp

实现代码

package com.hand.demo;

import java.io.*;

/**
 * 以文件格式
 * 导出临时表大量数据后 (由于数据量很大,不能直接打开临时表文件
 * 用一键替换的方式把临时表的表名改为正式表)
 *
 * 再插入正式表
 *
 * @author dujangzhou
 * @date 2023/8/1 10:17
 */
public class Demo23 {
    public static void main(String[] args) throws Exception {
        File file = new File("D://ES//lnk_scan_real_time_stock_temp.sql");
        operationFile(file);
    }

    public static void operationFile(File file) {

        try {
            InputStream is = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is));

            String filename = file.getName();
            // tmpfile为缓存文件,代码运行完毕后此文件将重命名为源文件名字。
            File tmpfile = new File(file.getParentFile().getAbsolutePath()
                    + "\\" + filename + ".sql");

            BufferedWriter writer = new BufferedWriter(new FileWriter(tmpfile));
            //替换的目标字符串
            String target = "lnk_scan_real_time_stock_temp";
            // 替换的字符串
            String newContent = "lnk_scan_real_time_stock";
            boolean flag = false;
            String str = null;
            int i = 0;
            while (true) {
                str = reader.readLine();
                i++;
                if (str == null) {
                    break;
                }
                //删除指定行数据
                if (i <= 69) {
                    System.out.println(str);
                    continue;
                }
                if (str.contains(target)) {
                    str = str.replace(target, newContent);
                    writer.write(str + "\n");
                    flag = true;
                } else {
                    writer.write(str + "\n");
                }
            }

            is.close();
            writer.flush();
            writer.close();

            if (flag) {
                file.delete();
                tmpfile.renameTo(new File(file.getAbsolutePath()));
            } else {
                tmpfile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

实现后效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值