如果我停止從管道輸入中讀取非程控輸入的程序,我會得到一個奇怪的錯誤(「該進程試圖寫入不存在的管道。」)。我怎樣才能避免造成這個錯誤?Java:正確處理管道作爲標準輸入
代碼:
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.
問題是您的操作系統使用反斜槓作爲其文件路徑分隔符。 (更直接地說,你使用Windows。) – AJMansfield 2013-12-17 16:48:34