【发布时间】:2018-10-28 02:39:26
【问题描述】:
我正在尝试使用 Apache Commons exec 解决与命令行进程的交互问题。我坚持使用以下代码:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream ins = new ByteArrayOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(ins);
BufferedWriter writer = new BufferedWriter(ow);
ByteArrayInputStream in = new ByteArrayInputStream(ins.toByteArray());
PumpStreamHandler psh = new PumpStreamHandler(out, null, in);
CommandLine cl = CommandLine.parse(initProcess);
DefaultExecutor exec = new DefaultExecutor();
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
exec.setStreamHandler(psh);
try {
exec.execute(cl, resultHandler);
int i = 0;
while (true) {
String o = out.toString();
if (!o.trim().isEmpty()) {
System.out.println(o);
out.reset();
}
// --- PROBLEM start ---
if (i == 3) {
writer.write(internalProcessCommand);
// string with or without trailing \n, both tested
writer.flush();
writer.close();
// tested even ins.write(internalProcessCommand.getBytes())
}
// --- PROBLEM end ---
Thread.sleep(3000);
i++;
}
} catch (ExecuteException e) {
System.err.println(e.getMessage());
}
我希望我的代码是清晰的。我不断阅读out 并在清除流时 3 秒后打印。问题是输入到in 传递给PumpStreamHandler。我需要从代码本身连续动态地传递进程命令,就好像我正在通过 CLI 与进程交互一样。当我简单地使用System.in 作为PumpStreamHandler 参数时,我可以很好地从控制台编写进程命令。我怎样才能设法从代码中传递相同的结果?
编辑:
我也尝试连接PipedInputStream从PipedOutputStream接收数据,但似乎只有在关闭PipedOutputStream后才能读取数据,这使得它无法重复使用,因此我无法实现交互。
编辑 2: 自己解决了。下面的答案中的解决方案。豪。 :-)
【问题讨论】:
标签: java inputstream apache-commons outputstream apache-commons-exec