Scanner + System.in stop condition [duplicate]
I'm reading a file with Scanner + System.in. My command in Linux looks like:
cat -A test.txt | java -jar test.jar
I'm reading input like:
Scanner input = new Scanner(System.in);
while (input.hasNextLine())
{
String log_line = input.nextLine();
}
The question is.. How I can stop reading when the end of file is reached?
The problem is that System.in
never "ends", i.e. EOF is never sent to the stream, so hasNextLine()
after the last line is blocking waiting for more data.
The solution is to pass the file name to your app, than you open FileInputStream(filePath)
and use it in Scanner constructor.
It seems that problem is -A option, not Your java code (it works correctly on plain files):
$ echo -e "foo\nbar" | java -jar Test.jar
foo
bar
$
Maybe test.txt contains some non-printable chars that Scanner can't handle...
精彩评论