0

I get a weird error ("The process tried to write to a nonexistent pipe.") if I stop reading from piped input, from a program that works fine for non-piped input. How can I avoid causing this error?

code:

package com.example.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PipeTest {
    static public void main(String[] args) throws IOException
    {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        int i = 0;
        while (i < 10)
        {
            String s = r.readLine();
            if (s == null)
                break;
            ++i;
            System.out.println(i);
        }
    }
}

runtime output (testfile.txt is just a large text file with more than 10 lines):

C:\proj\java\test-pipe\bin>java com.example.test.PipeTest < ../testfile.txt    
1
2
3
4
5
6
7
8
9
10

C:\proj\java\test-pipe\bin>type ..\testfile.txt | java com.example.test.PipeTest
1
2
3
4
5
6
7
8
9
10
The process tried to write to a nonexistent pipe.
4

1 回答 1

2

错误来自您的命令外壳,而不是来自 Java 程序。它之所以抱怨是因为“type”仍在尝试写入其输出,但是当 Java 程序终止时,该管道突然关闭。

于 2009-10-20T14:31:53.257 回答