• 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;  
        }  
    
    }
  • 相关阅读:
    C# DictionaryHelper
    C# Autofac 的 BeanFactory
    正则替换
    java页面表格导出为Excel实现
    CentOS 7 下安装Nginx
    认识Java 虚拟机的架构
    06 查看网卡实时流量
    05 找出占用CPU、内存过高的进程
    04 一键查看服务器资源利用率
    03 批量创建100个用户并设置随机密码
  • 原文地址:https://www.cnblogs.com/fangtest/p/3793812.html
Copyright © 2020-2023  润新知