All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.cliveyuan.robin.generator.util.FileContentModifyUtils Maven / Gradle / Ivy

/*
 * Copyright (c) 2020  Clive Yuan ([email protected]).
 */

package cn.cliveyuan.robin.generator.util;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件内容修改工具
 *
 * @author Clive Yuan
 * @date 2021/01/06
 */
@Slf4j
public class FileContentModifyUtils {

    public static void modify(String fileName, String startMark, String endMark, String content) {
        try {
            List newLines = new ArrayList<>();
            List lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
            int start = -1;
            int end = -1;
            for (int i = 0; i < lines.size(); i++) {
                String line = lines.get(i).trim();
                if (line.startsWith(startMark)) {
                    start = i;
                }
                if (line.contains(endMark)) {
                    end = i;
                    if (start >= 0) {
                        break;
                    }
                }
            }
            log.info("FileContentModifyUtils.modify start={}, end={}", start, end);
            if (start >= 0 && end >= 0) {
                for (int i = 0; i < lines.size(); i++) {
                    if (i < start || i > end) {
                        newLines.add(lines.get(i));
                    }
                }

                newLines.add(start, content);
                Files.write(Paths.get(fileName), newLines, StandardCharsets.UTF_8);
            } else {
                log.info("FileContentModifyUtils.modify can't find the segment to modify");
            }
        } catch (IOException e) {
            log.error("FileContentModifyUtils.modify error", e);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy