java 执行命令、调用bat文件、调用外部程序的两种方法

/**
* commons-exec.jar
* 根据路径执行文件
* @param path
* @return
* hb
*/
public static String exec(String path){

     if(StringUtil.isEmpty(path)){
         return null;
     }
     try {
     //创建一个命令行
     CommandLine cmdLine = CommandLine.parse(path);
     //参数一
     cmdLine.addArgument("pararm_1");
     //参数二
     cmdLine.addArgument("pararm_2");
     //执行流
     DefaultExecutor executor  = new DefaultExecutor();
     //定义一组预期退出值
     //executor.setExitValue(1);
     executor.setExitValues(null); 
     //监管机构-监管进程执行时间 --单位为毫秒
     ExecuteWatchdog watchdog = new ExecuteWatchdog(10);
     executor.setWatchdog(watchdog);

     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
     ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); 
     PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream);  
     executor.setStreamHandler(streamHandler);  

     int ex = executor.execute(cmdLine);

     //拿到执行程序中输出内容
     String out = outputStream.toString("gbk");  

      //拿到执行程序中执行异常内容
     String error = errorStream.toString("gbk");  

     Log.info(CommonsExecUtil.class, "Method[exec]执行命令行文件名称:{},执行输出:{},执行异常信息:{},执行结果:{}", path,out,error,ex);
    } catch (IOException e) {
        e.printStackTrace();
    }

     return null;
 }


 public static void main(String[] args) {
     exec("D:/svn/1.bat");
}

/****************java直接调用runtime****************************/

public void runbat(String batName) {
try {
Process ps = Runtime.getRuntime().exec(batName);
InputStream in = ps.getInputStream();
int c;
while ((c = in.read()) != -1) {
System.out.print(c);// 如果你不需要看输出,这行可以注销掉
}
in.close();
ps.waitFor();

    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("child thread done");
}

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值