zoukankan      html  css  js  c++  java
  • Java执行shell脚本并返回结果两种方法的完整代码

    https://www.cnblogs.com/zdz8207/p/java-linux-shell.html

    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;
        }
    复制代码
    大自然,飘然的风,QQ群: python技术交流群:453879716,人工智能深度学习群:251088643
    golang技术交流群:316397059,vuejs技术交流群:458915921 有兴趣的可以加入
    微信公众号:大自然预测(ssqyuce)原双色球预测, 心禅道(xinchandao),囤币一族(tunbitt)
  • 相关阅读:
    数据汇总计算和分析的反思
    排名算法计算
    仿Spring读取配置文件实现方案
    xml 配置文件规范 校验
    批量插入数据(基于Mybatis的实现-Oracle)
    shallow copy 和 deep copy 的示例
    引用对象的使用和易产生bug的示例
    codis安装手册
    Redis安装手册
    map和list遍历基础
  • 原文地址:https://www.cnblogs.com/zhoading/p/13439283.html
Copyright © 2011-2022 走看看