如何将字节数组写入流程构建器的 OutputStream (Java)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5119878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:32:33  来源:igfitidea点击:

How to write a byte array to OutputStream of process builder (Java)

javaioiostream

提问by Arran McCabe

byte[] bytes = value.getBytes();
Process q = new ProcessBuilder("process","arg1", "arg2").start();
q.getOutputStream().write(bytes);
q.getOutputStream().flush();
System.out.println(q.getInputStream().available());

I'm trying to stream file contents to an executable and capture the output but the output(InputStream) is always empty. I can capture the output if i specify the the file location but not with streamed input.

我正在尝试将文件内容流式传输到可执行文件并捕获输出,但输出(InputStream)始终为空。如果我指定文件位置而不是流输入,我可以捕获输出。

How might I overcome this?

我怎样才能克服这个问题?

回答by Kevin K

Try wrapping your streams with BufferedInputStream()and BufferedOutputStream():

尝试用BufferedInputStream()和包装你的流BufferedOutputStream()

http://download.oracle.com/javase/6/docs/api/java/lang/Process.html#getOutputStream%28%29

http://download.oracle.com/javase/6/docs/api/java/lang/Process.html#getOutputStream%28%29

Implementation note: It is a good idea for the output stream to be buffered.

Implementation note: It is a good idea for the input stream to be buffered.

实现说明:缓冲输出流是个好主意。

实现说明:缓冲输入流是个好主意。

Even with buffered streams, it is still possible for the buffer to fill if you're dealing with large amounts of data, you can deal with this by starting a separate thread to read from q.getInputStream(), so you can still be reading from the process while writing to the process.

即使使用缓冲流,如果您正在处理大量数据,缓冲区仍有可能被填满,您可以通过启动一个单独的线程来读取来处理这个问题q.getInputStream(),因此您仍然可以在写入时从进程中读取到过程。

回答by Philipp Wendler

Perhaps the program you execute only starts its work when it detects the end of its input data. This is normally done by waiting for an EOF (end-of-file) symbol. You can send this by closing the output stream to the process:

也许您执行的程序仅在检测到输入数据结束时才开始工作。这通常通过等待 EOF(文件结束)符号来完成。您可以通过关闭输出流来发送此进程:

q.getOutputStream().write(bytes);
q.getOutputStream().close();

Try this together with waiting for the process.

与等待过程一起尝试。

回答by kfis

I think, you have to wait, until the process finished. I implemented something like this this way:

我认为,您必须等待,直到该过程完成。我以这种方式实现了这样的事情:

public class ProcessReader {

  private static final int PROCESS_LOOP_SLEEP_MILLIS = 100;
  private String result;

  public ProcessReader(Process process) {
    BufferedReader resultReader = new BufferedReader(new   InputStreamReader(process.getInputStream()));
    StringBuilder resultOutput = new StringBuilder();
    try {
        while (!checkProcessTerminated(process, resultReader, resultOutput)) {
        }
    } catch (Exception ex1) {
        throw new RuntimeException(ex1);
    }
    result = resultOutput.toString();
}

public String getResult(){
    return result;
}

private boolean checkProcessTerminated(Process process, BufferedReader resultReader, StringBuilder resultOutput) throws Exception {

    try {
        int exit = process.exitValue();
        return true;
    } catch (IllegalThreadStateException ex) {
        Thread.sleep(PROCESS_LOOP_SLEEP_MILLIS);
    } finally {
        while (resultReader.ready()) {
            String out = resultReader.readLine();
            resultOutput.append(out).append("\n");
        }
    }
    return false;
}

}

}

I just removed now some specific code, that you dont need, but it should work, try it. Regards

我现在刚刚删除了一些您不需要的特定代码,但它应该可以工作,试试吧。问候

回答by Bernd Elkemann

I dont know if something else may also be wrong here, but the other process ("process") does not even have time to respond, you are not waiting for it (the method available() does not block). To try this out you can first insert a sleep(2000) after the flush(), and if that works you should switch to query'ing q.getInputStream().available() multipletimes with short pauses in between.

我不知道这里是否还有其他问题,但另一个进程(“进程”)甚至没有时间响应,您没有等待它(方法 available() 不会阻塞)。尝试了这一点,你冲洗(后第一次可以插入一个睡眠(2000)),以及是否工作,你应该用()切换到query'ing q.getInputStream()。多个次短暂停之间。