zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    浅谈REST[转]
    linuxyum
    XAMPPAccess denied for user 'root'@'localhost' (using password:YES)....& can't connect to localhost...
    ps aux详细解释【转】
    TOP 10:值得关注的十家云计算公司【转】
    isnull在数据库查询中的应用
    正则匹配代码
    推荐一款生成SQL插入语句的软件
    网页自动刷新
    执行SQL脚本语句判断是否已经存在
  • 原文地址:https://www.cnblogs.com/zdz8207/p/java-linux-shell.html
Copyright © 2011-2022 走看看