简体   繁体   English

多次编写OutputStream Pipleline错误-Java

[英]Writing OutputStream Pipleline multiple times error - java

I try to communicate with the process by using this way: 我尝试通过以下方式与流程进行通信:

Process process = Runtime.getRuntime().exec("/home/username/Desktop/mosesdecoder/bin/moses -f /home/username/Desktop/mosesdecoder/model/moses.ini");

while (true) {
    OutputStream stdin = null;
    InputStream stderr = null;
    InputStream stdout = null;
    stdin = process.getOutputStream();
    stderr = process.getErrorStream();
    stdout = process.getInputStream();

    // "write" the parms into stdin
    line = "i love you" + "\n";
    stdin.write(line.getBytes());
    stdin.flush();
    stdin.close();
    // Print out the output
    BufferedReader brCleanUp =
            new BufferedReader(new InputStreamReader(stdout));
    while ((line = brCleanUp.readLine()) != null) {
        System.out.println("[Stdout] " + line);
    }
    brCleanUp.close();
}

This works fine. 这很好。 However, I am stuck with a problem when I write the pipeline more than one time. 但是,当我多次编写管道时,我会遇到一个问题。 That is - I can write to the Outputstream pipeline more than one time. 也就是说-我可以多次写入Outputstream管道。 The error is (for the 2th iteration): 错误是(第二次迭代):

Exception in thread "main" java.io.IOException: **Stream Closed**
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:297)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.**flush(BufferedOutputStream.java**:140)
at moses.MOSES.main(MOSES.java:60)

So, is there any way to fix this problem? 那么,有什么办法可以解决这个问题?

In your while {} loop, you are calling stdin.close(). 在您的while {}循环中,您正在调用stdin.close()。 The first time through the loop, the stream is retrieved from the Process and happens to be open. 第一次通过循环,从流程中检索流并恰好打开了该流。 On the first iteration of the loop, the stream is retrieved from the process, written to, flushed, and closed(!). 在循环的第一次迭代中,从流程中检索流,将其写入,刷新和关闭(!)。 Subsequent iterations of the loop then get the same stream from the process, but it was closed on the first iteration of the loop (!), and your program throws an IOException . 然后,循环的后续迭代从进程中获得相同的流,但是在循环的第一次迭代(!)中将其关闭,并且您的程序将引发IOException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM