I Am Not Getting the Result I Expect Using readLine() in Java

前端 未结 3 838
一向
一向 2021-01-05 21:20

I am using the code snippet below, however it\'s not working quite as I understand it should.

public static void main(String[] args) {
    BufferedReader         


        
3条回答
  •  囚心锁ツ
    2021-01-05 21:56

    From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\r'.

    That is not correct. 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 ends, or if you're reading from a socket and the socket closses.

    But if you're simply reading the console input, hitting the return key on your keyboard does not constitute an end of stream. It's simply a character that is returned (\n or \r\n depending on your OS).

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

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

    Also, your current program should work as expected if you pipe some file directly into it, like so:

    java -cp . Echo < test.txt
    

提交回复
热议问题