栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java代码执行Linux命令

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java代码执行Linux命令

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

1. 工具类
@Controller
public class ExecuteNewFlowUtil {
    
    public List executeNewFlow(List commands) {
        List rspList = new ArrayList();
        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 generateComparativeInformationCommands = new ArrayList<>();
generateComparativeInformationCommands.add("命令1");
generateComparativeInformationCommands.add("命令2");
generateComparativeInformationCommands.add("命令3");
executeNewFlowUtil.executeNewFlow(generateComparativeInformationCommands);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/947126.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号