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

cn.schoolwow.util.module.replace.flow.ReplaceFileFlow Maven / Gradle / Ivy

The newest version!
package cn.schoolwow.util.module.replace.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.replace.domain.ReplaceFileOption;

import java.io.*;
import java.nio.file.Files;
import java.util.Map;

public class ReplaceFileFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ReplaceFileOption replaceFileOption = (ReplaceFileOption) flowContext.checkData("replaceFileOption");

        if(!replaceFileOption.file.exists()){
            throw new IllegalArgumentException("原始不存在!路径:["+replaceFileOption.file.getAbsolutePath()+"]");
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(replaceFileOption.file));
             BufferedWriter writer = new BufferedWriter(new FileWriter(replaceFileOption.file.getName() + ".tmp"));
        ){
            String line;
            while ((line = reader.readLine()) != null) {
                String modifiedLine = line;
                //普通字符串替换
                for (Map.Entry entry : replaceFileOption.replaceStringMap.entrySet()) {
                    modifiedLine = modifiedLine.replace(entry.getKey(), entry.getValue());
                }
                //正则替换
                for (Map.Entry entry : replaceFileOption.regexReplaceStringMap.entrySet()) {
                    modifiedLine = modifiedLine.replaceAll(entry.getKey(), entry.getValue());
                }
                writer.write(modifiedLine);
                writer.newLine();
            }
        }
        Files.deleteIfExists(replaceFileOption.file.toPath());
        File renameFile = new File(replaceFileOption.file.getName() + ".tmp");
        Files.move(renameFile.toPath(), replaceFileOption.file.toPath());
    }

    @Override
    public String name() {
        return "替换文件内容";
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy