exec java -jar_Java 执行系统命令工具类(commons-exec)

packageutils;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.OutputStream;importorg.apache.commons.exec.CommandLine;importorg.apache.commons.exec.DefaultExecutor;importorg.apache.commons.exec.ExecuteException;importorg.apache.commons.exec.ExecuteWatchdog;importorg.apache.commons.exec.PumpStreamHandler;/*** 执行系统命令工具类

*

*@authorStorm

**/

public classCommandUtils {private static final String DEFAULT_CHARSET = "GBK";/*** 执行指定命令

*

*@paramcommand 命令

*@return命令执行完成返回结果

*@throwsIOException 失败时抛出异常,由调用者捕获处理*/

public static String exeCommand(String command) throwsIOException {try(

ByteArrayOutputStream out= newByteArrayOutputStream();

) {int exitCode =exeCommand(command, out);if (exitCode == 0) {

System.out.println("命令运行成功!");

}else{

System.out.println("命令运行失败!");

}returnout.toString(DEFAULT_CHARSET);

}

}/*** 执行指定命令,输出结果到指定输出流中

*

*@paramcommand 命令

*@paramout 执行结果输出流

*@return执行结果状态码:执行成功返回0

*@throwsExecuteException 失败时抛出异常,由调用者捕获处理

*@throwsIOException 失败时抛出异常,由调用者捕获处理*/

public static int exeCommand(String command, OutputStream out) throwsExecuteException, IOException {

CommandLine commandLine=CommandLine.parse(command);

PumpStreamHandler pumpStreamHandler= null;if (null ==out) {

pumpStreamHandler= newPumpStreamHandler();

}else{

pumpStreamHandler= newPumpStreamHandler(out);

}//设置超时时间为10秒

ExecuteWatchdog watchdog = new ExecuteWatchdog(10000);

DefaultExecutor executor= newDefaultExecutor();

executor.setStreamHandler(pumpStreamHandler);

executor.setWatchdog(watchdog);returnexecutor.execute(commandLine);

}public static voidmain(String[] args) {try{

String result= exeCommand("ipconfig /all");

System.out.println(result);

}catch(IOException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值