2

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();
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • It seems to work? Can you give any more details? – David Conrad Nov 15 '21 at 23:27
  • maybe The problem is from eclipse as I'm actually using it. – Aymen Soussi Nov 16 '21 at 00:42
  • 2
    Sounds like the last line in file.txt does not end with a newline. – MTilsted Nov 16 '21 at 13:54
  • Note that you can also read the text file using NIO, `Files.readAllLines(...)`, `Files.lines(...)`, `Files.readString(...)`. Just saying, in case you want an alternative to piping via `System.in`. – Zabuzard Nov 16 '21 at 13:58
  • @MTilsted the absence of a end-of-line / new line at the end of the file should not prevent the buffered reader from detecting the end of file and reporting it as a new line. From the documentation : "Returns : A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached" – GPI Nov 16 '21 at 17:10

2 Answers2

1

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
Manifest Man
  • 873
  • 10
  • 16
1

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);
DuncG
  • 12,137
  • 2
  • 21
  • 33