javastdinbufferedreaderinputstreamreader

Is there a way to avoid the "hit enter key" when reading lines from stdin using BufferedReader?


The following is a simple but fully working Java program that demonstrates my issue:

package bufferedreader_test;

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

public class BufferedReaderTest {

    public static void main(String[] args) {
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            String line[] = new String[2];

            for (int i=0; i<2; i++) 
                line[i] = br.readLine();

            for (int j=0; j<line.length; j++)
                System.out.println(line[j]);
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

If you copy & paste 2 lines into the console, it will not print them immediately but rather wait for you to hit the Enter key (i.e. inject a newline into stdin).

For example:

enter image description here

Is there a way to "trick the system" into printing the result as soon as the 2nd line is read, without waiting for the Enter key (3rd line?) ?


Solution

  • You have two problems:

    1. The console doesn't actually send anything to your program until you press ENTER. This allows you to edit the line before submitting it. There are OS-specific ways to get around this, but nothing you can do about it in pure/portable java.

    2. br.readLine() doesn't know the line has ended until it receives the linefeed character that the console puts at the end of the text when you press ENTER. Without the enter key, how would it know that you were done typing? You could also type your OS-specific EOF character (probably ctrl-Z or ctrl-D) to terminate console input, but that's probably not what you want.

    If you only want to solve this problem for manual copy and paste, then maybe you can just select the linefeed before you copy, by dragging all the way to line 3.