Reading last line from Std input when last line does not contain a new line character

时间:2015-11-12 11:20:00

标签: java

Well I know this is a pretty basic question but somehow I am not able to figure it out.

I have an input similar to say:

line1
line2
line3
line4

All the lines have a new line character at the end except line4 i.e. I have pressed ENTER after each line except line4. Now if I provide this as an input to the BufferedReader, it reads out only the first 3 lines and skips the last line.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line=br.readLine())!=null){  
    System.out.println(line);
}

This is the code I am trying to use. I dont think there is any problem with the code and no new line at the last line is causing the problem.

Can someone help me with this.

1 个答案:

答案 0 :(得分:0)

From BufferedReader's readLine() javadoc:

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Meaning, if you want to "read" a line, it has to have one of those characters mentioned above.