zoukankan      html  css  js  c++  java
  • java调用linux脚本 shell

      最近项目需要用java调用shell,在网找找了些文章,总结如下:

    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.LineNumberReader;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Shell {
        
        public static void main(String[] args) {
            try {
                runShell("/root/shell/test.sh arg1 arg2 arg3");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        
        /**
         * 调用shell,
         * parameter:arg1  arg2 arg3,
         * return  void
         * */
        public void callShell(){
            try {
                Runtime rt = Runtime.getRuntime();  
                rt.exec("/root/shell/test.sh arg1 arg2 arg3");
            } catch (IOException e) {
                e.printStackTrace();
            }  
        }
        
        /** 
         * 运行shell 
         *  
         * @param shStr  需要执行的shell绝对路径 和参数 
         * @return echo 打印结果保存在list中,shell中echo值放到list中
         * @throws IOException 
         */  
        public static List runShell(String shStr) throws Exception {  
            List<String> strList = new ArrayList();  
      
            Process 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);  
                System.out.println(line);
            }  
            return strList;  
        }  
    
    }
  • 相关阅读:
    hdoj 1879 继续畅通工程
    hdoj 1233 还是畅通工程
    PAT-1107 Social Clusters (30 分)
    hdoj 1232 畅通工程
    POJ-3061 前缀和+二分搜索 模板题
    常见推荐系统框架
    常见的时间衰减函数
    英语中的五大基本句型
    如何获得excel文件名和工作表名
    记一次atomikos 连接池耗尽错误
  • 原文地址:https://www.cnblogs.com/fangtest/p/3793812.html
Copyright © 2011-2022 走看看