BufferedReader stuck at last input line without ending the program

614 Views Asked by At

I'm using BufferedReader to read data from System.in (a text file redirected context: < file.txt) then write it to the console. The problem is my program shows all lines except the last one and still works without doing any thing. If I manually end it it will write the final line.

This is my code:

public void updateText() throws IOException {
    try {
    InputStreamReader inputStreamReader = new InputStreamReader(System.in);         
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

    String inputLine;
 
    while ((inputLine = bufferedReader.readLine()) != null) {

         System.out.println(inputLine);

    }
    
    inputStreamReader.close();
    bufferedReader.close();
        
    } catch (IOException e) {
        e.printStackTrace();
    }
}
2

There are 2 best solutions below

4
Manifest Man On BEST ANSWER

Here an alternative way of waiting on available data (Ref.: Java 11 - method BufferedReader.ready()):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class TestClass {
    public static void main(String[] args) {

        try (InputStreamReader inputStreamReader = new InputStreamReader(System.in);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            String line;
            // wait until data available
            while (!bufferedReader.ready()){
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Example output:

Hello world 
Hello world 
Hello world
Hello world
0
DuncG On

If this only occurs in Eclipse, your issue is most likely a duplicate and bug 513713.

You don't need to read standard input line by line when you could simply transfer the data in one step, replacing the body of updateText():

System.in.transferTo(System.out);