java - 多次写入输出流管道错误 - java

标签 java pipeline

我尝试使用这种方式与进程进行通信:

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();
}

这很好用。然而,当我多次编写管道时,我遇到了一个问题。也就是说,我可以多次写入 Outputstream 管道。错误是(第二次迭代):

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)

那么,有什么办法可以解决这个问题吗?

最佳答案

while {} 循环中,您正在调用 stdin.close()。第一次通过循环时,从 Process 中检索流并且碰巧打开了该流。在循环的第一次迭代中,从进程中检索流、写入、刷新并关闭(!)。循环的后续迭代然后从进程中获取相同的流,但它在循环的第一次迭代时关闭 (!),并且您的程序会抛出 IOException

关于java - 多次写入输出流管道错误 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14188385/

相关文章:

java - 使用反射在方法中检索类

Java Server Faces Ajax 请求无法正常工作

mongodb - 如何在 Mongo 中合并列

mysql - Scrapy/Pipeline 未将数据插入 MySQL 数据库

Scikit-Learn:在交叉验证期间避免数据泄漏

airflow - 如何将自定义组件添加到 Elyra 的可用 Airflow 操作符列表中?

java - 将时间戳转换为字符串而不指定格式

java - 如何在另一个类中调用一个类的main方法?

java - 如何更新测试类中intellij idea插件的持久状态?

memory - 经典 RISC 管道 - "memory access"阶段实际上做了什么?