我正在尝试使用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
的{{1}}。我需要连续动态地从代码本身传递进程命令,就像我通过CLI与进程交互一样。当我只使用PumpStreamHandler
作为System.in
参数时,我可以从控制台中编写流程命令。如何设置从代码中传递相同的结果?
修改
我还尝试连接PumpStreamHandler
从PipedInputStream
接收数据,但似乎只有在关闭PipedOutputStream
之后才能读取数据,这使得它无法重复使用,因此我无法实现交互性。 / p>
编辑2: 解决了自己。解答如下。 Howgh。 : - )
答案 0 :(得分:1)
一个解决方案是复制 PumpStreamHandler 和 StreamPump 的实现,比如 ImmediatePumpStreamHandler 和 ImmediateStreamPump,并进行以下两个更改:
os.flush();
之后直接添加 os.write(buf, 0, length);
。new StreamPumper(...)
更改为 new ImmediateStreamPump(...)
。答案 1 :(得分:0)
好的,我使用内置工具而不是外部库解决了这个问题。由于独立的帖子显示Process
'InputStream
,我能够实现我的目标:
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
StreamReader outputReader = new StreamReader(process.getInputStream(), System.out);
outputReader.start();
StreamReader err = new StreamReader(process.getErrorStream(), System.err);
err.start();
for (int i = 0; i < 3; i++) {
Thread.sleep(5000);
writer.write(internalProcessCommand + "\n");
writer.flush();
}
writer.write("exit\n");
writer.flush();
while (process.isAlive()) {
System.out.println("alive?");
Thread.sleep(100);
}
System.out.println("dead");
outputReader.shutdown();
err.shutdown();
的StreamReader:
class StreamReader extends Thread {
private AtomicBoolean running = new AtomicBoolean(false);
private InputStream in;
private OutputStream out;
public StreamReader(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
running.set(true);
}
@Override
public void run() {
Scanner scanner = new Scanner(in);
PrintWriter writer = new PrintWriter(out, true);
while (running.get()) {
if (scanner.hasNextLine()) {
writer.println(scanner.nextLine());
}
}
scanner.close();
}
public void shutdown() {
running.set(false);
}
}
答案 2 :(得分:0)
根据@champagniac 给出的答案,我创建了一个简单的修复程序,它通过仅替换 PumpStreamHandler
来引入额外的冲洗:
public class PumpStreamHandlerFixed extends PumpStreamHandler
{
public PumpStreamHandlerFixed()
{
super();
}
public PumpStreamHandlerFixed(OutputStream out, OutputStream err, InputStream input)
{
super(out, err, input);
}
public PumpStreamHandlerFixed(OutputStream out, OutputStream err)
{
super(out, err);
}
public PumpStreamHandlerFixed(OutputStream outAndErr)
{
super(outAndErr);
}
@Override
protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted)
{
os = new AutoFlushingOutputStream(os);
final Thread result = new Thread(new StreamPumper(is, os, closeWhenExhausted), "Exec Stream Pumper");
result.setDaemon(true);
return result;
}
}
class AutoFlushingOutputStream extends OutputStream
{
private final OutputStream decorated;
public AutoFlushingOutputStream(OutputStream decorated)
{
this.decorated = decorated;
}
@Override
public void write(byte[] b, int off, int len) throws IOException
{
this.decorated.write(b, off, len);
this.decorated.flush();
}
@Override
public void write(int b) throws IOException
{
this.decorated.write(b);
this.decorated.flush();
}
@Override
public void close() throws IOException
{
this.decorated.close();
}
@Override
public void flush() throws IOException
{
this.decorated.flush();
}
}