java/Commons-exec

本文介绍了如何在Java中执行命令并输出中文编码的过程,包括命令解析、参数添加、流处理以及超时设置等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

命令输出中文编码

String line=”ping “;
CommandLine cmdLine=CommandLine.parse(line);
cmdLine.addArgument(“www.baidu.com”);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream);
DefaultExecutor executor=new DefaultExecutor();
executor.setStreamHandler(streamHandler);
int exitValue=executor.execute(cmdLine);
String out =outputStream.toString(“gbk”);
String error =errorStream.toString(“gbk”);
System.out.println(exitValue);
System.out.println(out);

监视超时

//利用监视狗来设置超时
ExecuteWatchdogwatchdog = new ExecuteWatchdog(60000);
exec.setWatchdog(watchdog);

默认执行外部命令是阻塞式的,在执行命令时,当前线程是阻塞的。可以使用DefaultExecuteResultHandler处理外部命令执行的结果,释放当前线程。

DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
executor.execute(cmdLine, resultHandler);
//阻塞当前线程
resultHandler.waitFor();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值