本文共 1709 字,大约阅读时间需要 5 分钟。
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();
}
}
}
转载地址:https://blog.csdn.net/weixin_32042443/article/details/115068513 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!