Java执行shell脚本并返回结果两种方法的完整代码

Java执行shell脚本并返回结果两种方法的完整代码

简单的是直接传入String字符串,这种不能执行echo 或者需要调用其他进程的命令(比如调用postfix发送邮件命令就不起作用)

执行复杂的shell建议使用String[]方式传递(对外可以封装后也传入String字符串)。

 

复制代码
/**
     * 运行shell脚本
     * @param shell 需要运行的shell脚本
     */
    public static void execShell(String shell){
        try {
            Runtime.getRuntime().exec(shell);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 运行shell脚本 new String[]方式
     * @param shell 需要运行的shell脚本
     */
    public static void execShellBin(String shell){
        try {
            Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shell},null,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    /**
     * 运行shell并获得结果,注意:如果sh中含有awk,一定要按new String[]{"/bin/sh","-c",shStr}写,才可以获得流
     * 
     * @param shStr
     *            需要执行的shell
     * @return
     */
    public static List<String> runShell(String shStr) {
        List<String> strList = new ArrayList<String>();
        try {
            Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null);
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            process.waitFor();
            while ((line = input.readLine()) != null){
                strList.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strList;
    }
复制代码

 

posted @ 2019-07-29 01:10  大自然的流风  阅读(28998)  评论(0)    收藏  举报
编辑推荐:
· 协程本质是函数加状态机——零基础深入浅出 C++20 协程
· 编码之道,道心破碎。
· 记一次 .NET 某发证机系统 崩溃分析
· 微服务架构学习与思考:SOA架构与微服务架构对比分析
· tomcat为什么假死了
阅读排行:
· 知名开源项目Alist被收购!惹程序员众怒,开团炮轰甲方
· 突发,小红书开发者后门被破解?!
· 历时半年,我将一个大型asp.net的零代码快速开发平台转成了java
· [原创]《C#高级GDI+实战:从零开发一个流程图》第03章:画一个线,连接两个矩形!
· C# 将 CSV 转化为 Excel
点击右上角即可分享
微信分享提示