我正在尝试使用 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: 解决了自己。下面的答案中的解决方案。豪。:-)