Java调用Shell脚本

本文介绍了一个Java程序如何通过Runtime.getRuntime().exec方法来执行Shell脚本的示例,并展示了具体的实现代码及synRes.sh脚本内容。
package com.lshop.common.util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.lshop.html.action.InitIndexAction;
public class ShellUtil {
     private static final Log logger = LogFactory.getLog(InitIndexAction.class);
     
  public static boolean ExeShell(String shellPath){  
//    String cmd = "/usr/bin/rsync -av /var/log/www.solive.kv/access_log testuser@10.0.1.219::store --password-file=/etc/client/rsync.pwd";
      String cmd = "sh /www/www.itvpad.com/www/manager/synRes.sh"+;
      System.out.println(cmd);
      Runtime run = Runtime.getRuntime();
      String result = "";
      BufferedReader br=null;
      BufferedInputStream in=null;
      try {
       Process p = run.exec(cmd);
       if(p.waitFor() != 0){  
        result+="没有进程号";
              return false;  
       }    
       in = new BufferedInputStream(p.getInputStream());
       br = new BufferedReader(new InputStreamReader(in));
       String lineStr;
       while ((lineStr = br.readLine()) != null) {
             result += lineStr;
          }
      } catch (Exception e) {
       e.printStackTrace();
       return false;
      }finally{
       if(br!=null){
           try {
      br.close();
      in.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
       }
       logger.info("ShellUtil.ExeShell=>"+result);
      }
      return true;
  }
}

synRes.sh脚本内容

#!/bin/sh

pwd

不知道这种情况怎么不能实现,如有人知道忘解答。

String[] cmd = {"/bin/sh", "-c", shellCommand};
//执行Shell命令
Process pid = Runtime.getRuntime().exec(cmd);

转载于:https://my.oschina.net/ukapollo/blog/192052

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值