说明:项目必须是部署在Linux服务器中才能生效。

1. 工具类

@Controller
public class ExecuteNewFlowUtil {
    /**
     * 运行Linux命令
     * @author YuanRiKang
     * @date 2022/5/24 16:56
     * @param commands 命令集合
     * @return 返回结果
     */
    public List<String> executeNewFlow(List<String> commands) {
        List<String> rspList = new ArrayList<String>();
        Runtime run = Runtime.getRuntime();
        try {
            Process proc = run.exec("/bin/bash", null, null);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            for (String line : commands) {
                out.println(line);
            }
            out.println("exit");// 这个命令必须执行,否则in流不结束。
            String rspLine = "";
            while ((rspLine = in.readLine()) != null) {
                System.out.println(rspLine);
                rspList.add(rspLine);
            }
            proc.waitFor();
            in.close();
            out.close();
            proc.destroy();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return rspList;
    }
}

2.方法执行代码段

//运行命令生成对比信息
List<String> generateComparativeInformationCommands = new ArrayList<>();
generateComparativeInformationCommands.add("命令1");
generateComparativeInformationCommands.add("命令2");
generateComparativeInformationCommands.add("命令3");
executeNewFlowUtil.executeNewFlow(generateComparativeInformationCommands);

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐