patriques patriques - 4 days ago 6
Java Question

BufferedReader not blocking for input

I have tried two versions but both repeatedly prints out the else part of the program.

Version 1 (with line break)

try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
while(true) {
String input = br.readLine();
if(input != null) {
SomeRequest req = new SomeRequest();
req.text = input;
client.sendTCP(req);
} else {
System.out.println("non stop..."); <-- this continously prints
}
}
}


Version 2 (with no new line)

try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
while(true) {
String input = br.readLine();
if(input != null) {
SomeRequest req = new SomeRequest();
req.text = input;
client.sendTCP(req);
} else {
System.out.print("non stop..."); <-- this continously prints as well?
}
}
}


Version 3 (throws exception)

try(Scanner sc = new Scanner(System.in)) {
String input = "";
System.out.println("Enter to send");
while(true) {
if(!sc.hasNextLine()) {
input = sc.nextLine();
SomeRequest req = new SomeRequest();
req.text = input;
client.sendTCP(req);
} else {
System.out.println("not sending");
}
}
}


Im trying to let the user print something on the console to send it to a server as you can see. But right now the program simply prints non stop...

EJP EJP
Answer

Both versions are invalid. You're not exiting the loop at end of stream. It should be:

try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
    String input;
    while ((input = br.readLine()) != null) {
        SomeRequest req = new SomeRequest();
        req.text = input;
        client.sendTCP(req);
        }
    }
    System.out.print("End of input");
}
Comments