Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe input to Java program with bash

My Java program is listening on standard input:

InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader bufReader = new BufferedReader(isReader);
while(true){
    try {
        String inputStr = null;
        if((inputStr=bufReader.readLine()) != null) {
            ...
        }
        else {
            System.out.println("inputStr is null");
        }
    }
    catch (Exception e) {
        ...
    }
}

Now, I want to pipe input to this program from bash. I tried the following:

echo "hi" | java -classpath ../src test.TestProgram

But it's just printing inputStr is null infinite times. What am I doing wrong?

Edit 1: Updated question to include more code / context.


Edit 2:

Looks like I'm experiencing the same issue as this OP: Command Line Pipe Input in Java

How can I fix the program so that I can pipe input in for testing, but running the program normally will allow users to enter input on standard input as well?

like image 918
Chetan Avatar asked Sep 07 '25 06:09

Chetan


2 Answers

You have while(true), so infinite looping is what you're going to get.

Adding a break somewhere in the loop is one way to fix it. But it's not good style, because the reader has to hunt around the loop to find out if and when it exits.

It's much better to make your while statement show clearly what the exit condition is:

String inputStr = "";
while(inputStr != null) {
    inputStr=bufReader.readLine(); 
    if(inputStr != null) {
        ...
    } else {
        System.out.println("inputStr is null");
    }
}
like image 156
slim Avatar answered Sep 08 '25 21:09

slim


Fixed it. After the piping of input was completed, readLine() kept returning null, so the infinite loop kept looping.

The fix is to break from the infinite loop when readLine() returns null.

like image 37
Chetan Avatar answered Sep 08 '25 19:09

Chetan