读取文件内容,根据关键字删除某几行数据

package com.geekmice.springbootselfexercise.utils;

import com.geekmice.springbootselfexercise.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.Objects;

/**
 * @BelongsProject: spring-boot-self-exercise
 * @BelongsPackage: com.geekmice.springbootselfexercise.utils
 * @Author: pingmingbo
 * @CreateTime: 2023-08-15  21:36
 * @Description: 文件操作工具类
 * @Version: 1.0
 */
@Slf4j
public class FileUtil {

    /**
     * 文件目录
     */
    public static final String PATH_PREFIX = "D:\\huasukeji\\spring-boot-self-exercise\\src\\main\\java\\com\\geekmice\\springbootselfexercise\\file\\";

    /**
     * 根据关键字删除文件内容所在行,生成新的文件
     * @param absolutePath 文件地址
     * @param keyword 关键字
     */
    public static void delFileContentByKeyword(String absolutePath, String keyword) {
        StringBuilder concatBuffer = new StringBuilder();
        concatBuffer.append(PATH_PREFIX);
        if (StringUtils.isEmpty(absolutePath)) {
            absolutePath = "source.txt";
        }
        concatBuffer.append(absolutePath);
        StringBuilder buffer = new StringBuilder();
        int lineNum = 1;
        /**
         * 1 读取文件内容
         */
        try (BufferedReader reader = new BufferedReader(new FileReader(concatBuffer.toString()))) {
            while (true) {
                String line = reader.readLine();
                if (Objects.isNull(line)) {
                    log.info("第【{}】是最后一行", lineNum);
                    break;
                }

                if (line.contains(keyword)) {
                    log.info("删除的行号:【{}】", lineNum);
                    lineNum++;
                    continue;
                }
                buffer.append(line).append("\n");
                log.info("第【{}】,line:【{}】", lineNum, line);
                lineNum++;
            }
        } catch (IOException e) {
            log.error("params:【{}】,error msg:【{}】", lineNum, lineNum);
            lineNum++;
        }

        /**
         * 2 写入文件内容
         */
        String targetPath = concatBuffer.toString();
        String handlePath = targetPath.replace("source", "target");
        try (PrintWriter printWriter = new PrintWriter(handlePath)) {
            log.info("targetPath:【{}】", handlePath);
            printWriter.println(buffer.toString());
        } catch (FileNotFoundException e) {
            log.error("params :【{}】,error msg:【{}】", handlePath, e);
            throw new BusinessException("error msg:【".concat(e.toString()).concat("】"));
        }

    }
}

你可能感兴趣的:(问题汇总,开发语言,java)