Java代码执行Linux命令

编程知识 更新时间:2023-04-07 06:15:43

说明:项目必须是部署在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);

更多推荐

Java代码执行Linux命令

本文发布于:2023-04-07 06:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/937541bdf0b7055ec72a2cf6766237b5.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:命令   代码   Java   Linux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 52484文章数
  • 14阅读数
  • 0评论数