Java调用shell脚本

最近的新项目有多个地方需要调用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

posted @ 2017-09-30 17:52  逐鹿者  阅读(911)  评论(0编辑  收藏  举报