如果我停止从适用于非管道输入的程序中读取管道输入,我会收到一个奇怪的错误(“该进程试图写入不存在的管道。”)。如何避免导致此错误?
代码:
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);
}
}
}
运行时输出(testfile.txt只是一个超过10行的大文本文件):
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.
最佳答案
该错误来自您的命令 shell,而不是来自 Java 程序。它提示是因为“type”仍在尝试写入其输出,但当 Java 程序终止时该管道突然关闭。
关于Java:正确处理管道作为标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1594940/