java exec封装_Java 执行系统命令工具类(commons-exec)
发布日期:2021-06-24 10:12:01 浏览次数:4 分类:技术文章

本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:php sha512解密,PHP加密函数 sha256 sha512 sha256_file() sha512_file()
下一篇:ajax php mysql数据库密码_jquery ajax 验证前台用户输入的密码是否与数据库的密码一致的代码(php的,肯定是jquery的代码)...

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月21日 15时56分31秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章