-3

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?

Serhiy
  • 4,073
  • 3
  • 36
  • 66

2 Answers2

3

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.

Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • strangely, but it works for me (just copy/pasted Serhiy's code and added line echoing to stdout) :) – barti_ddu Nov 30 '10 at 16:12
  • Myabe there is some alternative to Scanner? I didn't want to pass fileneame through args.. – Serhiy Nov 30 '10 at 16:19
  • I'm not arguing Your solution (it is better/safer), just curious: http://img13.imageshack.us/img13/3706/scanner.png – barti_ddu Nov 30 '10 at 16:21
2

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...

barti_ddu
  • 10,179
  • 1
  • 45
  • 53
  • test.txt is file generated by another program and all characters looks like fine.. What do you mean with echo? Echo doens't display the content of the file? Previously I was using tail command and the probalem there is with condition to stop..I think so.. – Serhiy Nov 30 '10 at 15:54
  • I've used echo just for convenience; it doesn't make much difference (and yes, something like `echo -e "1\n2\n3" > test.txt | tail -n 2 test.txt | java -jar dist/Test.jar 2 3 ` works too. By the way, what terminal emulator do You use? – barti_ddu Nov 30 '10 at 16:07
  • Omg, I must be really stupid or really tired.. Another thread I have wasn't stopping so the program won't exit. THanks a lot for help. – Serhiy Nov 30 '10 at 16:30