首页 > 编程语言 > 详细

Java调用shell脚本

时间:2017-09-30 18:49:37      阅读:250      评论:0      收藏:0      [点我收藏+]

最近的新项目有多个地方需要调用shell脚本,这里记录下简单的shell脚本调用方法。代码如下:

 

private void callSh() {
  InputStreamReader stdISR = null; 
        InputStreamReader errISR = null; 
        Process process = null;
  //调用的脚本及路径
  String command = "/home/mw/weblogic/test.sh"; 
  try {
   process = Runtime.getRuntime().exec(command);
   BufferedReader stdBR = new BufferedReader(new InputStreamReader(process.getInputStream()));
   BufferedReader errBR = new BufferedReader(new InputStreamReader(process.getErrorStream()));
         String line = ""; 
         while ((line = stdBR.readLine()) != null) { 
             System.out.println("STD line:" + line); 
         }
   
   while ((line = errBR.readLine()) != null) { 
             System.out.println("ERR line:" +line); 
         }
        
  } catch (Exception e) {
   throw new BusinessException("执行脚本失败===="+e);
  }finally{
   if(stdBR != null){
    stdBR.close(); 
   }
   if(errBR != null){
    errBR.close();
   }
   if(process != null){
    process.destroy();
   }
   
  }
  
 }

 

此代码只适用一般的shell脚本调用,如果shell脚本内容比较多,语法比较复杂,因为没有很好的容错机制,使用此方式可能就会出现问题。这里看过一篇文章,可借鉴:

http://blog.csdn.net/lance_wyvern/article/details/50456903#comments

Java调用shell脚本

原文:http://www.cnblogs.com/runnigwolf/p/7615775.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!