package io.wdd.common.utils; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Component public class FunctionReader { public static List> ReadFileToCommandList(String functionFilePath) { // https://www.digitalocean.com/community/tutorials/java-read-file-line-by-line List> result = null; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(functionFilePath)); result = doReadContent( result, bufferedReader ); } catch (IOException e) { throw new RuntimeException(e); } return result; } public static List> ReadStringToCommandList(String functionContent) { List> result = null; try { // 构造一个 buffered Reader BufferedReader bufferedReader = new BufferedReader( new StringReader(functionContent) ); // 执行read操作 result = doReadContent( result, bufferedReader ); } catch (IOException e) { throw new RuntimeException(e); } return result; } /** * 实际解析从前端传入的 脚本命令, 将其转换为 List> * * @param result * @param bufferedReader * @return * @throws IOException */ private static List> doReadContent(List> result, BufferedReader bufferedReader) throws IOException { String line = bufferedReader.readLine(); if (line != null) { result = new ArrayList<>(64); } while (line != null) { if (!StringUtils.isEmpty(line)) { result.add(SplitSpaceIndentToCommandList(line)); } line = bufferedReader.readLine(); } return result; } public static List SplitSpaceIndentToCommandList(String commandLine) { return Arrays .stream(commandLine .split(" ")) .collect(Collectors.toList()); } public static List SplitCommaIndentToCommandList(String commandLine) { // 需要进行归一化,去除掉多余的空格 return Arrays .stream(commandLine.split(",")) .map( split -> split.replace( " ", "" ) ) .collect(Collectors.toList()); } }