I do not get the result that I expect using readLine () in Java

I am using the code snippet below, however it does not work as I understand it.

public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; try { line = br.readLine(); while(line != null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } 

Reporting to Javadoc about readLine() , he says:

Reads text. A line is considered to be completed by any of the lines ( \n ), carriage return ( \r ) or carriage return, which the line immediately follows.

Returns : A String containing the contents of the string, not including end-of-line characters, or null if end of stream is reached

Throws : IOException - If an I / O error has occurred

From my understanding of this, readLine should return null the first time that input is not entered other than line termination, such as \r . However, this code simply ends endlessly. After debugging, I found that instead of null, returned when you enter only the termination character, it actually returns an empty string (""). It makes no sense to me. What I do not understand correctly?

+4
source share
3 answers

From my understanding of this, readLine should return null the first time that input is not entered other than line termination, such as '\ r'.

This is not true. readLine will return null if the end of the stream is reached. That is, for example, if you are reading a file and the file is ending, or if you are reading a socket and sockets.

But if you just read the console input, pressing the return key on the keyboard is not the end of the stream. It is just a character that is returned ( \n or \r\n depending on your OS).

So, if you want to split both the empty line and the end of the line, you should do:

 while (line != null && !line.equals("")) 

In addition, your current program should work as expected if you connect any file directly to it, for example:

 java -cp . Echo < test.txt 
+10
source

No input matches the end of the stream. Usually you can simulate the end of a stream in the console by pressing Ctrl + D (on some systems AFAIK uses Ctrl + Z ). But I assume that this is not what you want, in order to better check empty strings additionally for null strings.

+3
source

There is a good apache commons lang library that has good api for ordinary actions. You can use the static import of StringUtils and use its isNotEmpty (String) method to get:

 while(isNotEmpty(line)) { System.out.println(line); line = br.readLine(); } 

It may be useful someday :) There are other useful classes in this library.

+1
source

Source: https://habr.com/ru/post/1276419/


All Articles