javabufferedreaderinputstreamreadersystem.in

BufferedReader stuck at last input line without ending the program


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();
    }
}

Solution

  • 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