开发者

Scanner + System.in stop condition [duplicate]

This question already has an answer here: How to use java.util.Scanner to correctly read user input from System.in and act on it? (1 answer) Closed 5 years ago. 开发者_StackOverflow社区

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜