asadek
asadek

Reputation: 1

Reading InputStream from Java Interactive Process using ProcessBuilder

I am trying to run an interactive executable from Java application using ProcessBuilder; it's supposed to take input, produce output and then wait for the next input. The main problem here with Input/Output streams. I send an input and get nothing. Here is the code:

private static Process process;
private static BufferedReader result;
private static PrintWriter input;

process = new ProcessBuilder("compile-lm", lmFile.toString(), " --score yes").redirectErrorStream(true).start();

input = new PrintWriter(new OutputStreamWriter(process.getOutputStream()), true);
input.println(message);
System.out.println(message);

result = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = new String();

while ((line = result.readLine()) != null)
{

/* Some processing for the read line */

System.out.println("output:\t" + line);
}

Upvotes: 0

Views: 3008

Answers (3)

zizoujab
zizoujab

Reputation: 7800

I have tried your code it works fine there is no problem with the code. I think that the problem with the command that you are trying to execute ( it returns nothing ). try to change parameters or even change the entire command to test. and if you can execute the comand in other place ( terminal for example try it and see the output with the same parameters )

Upvotes: 1

user207421
user207421

Reputation: 310919

Try closing the output stream to the process. Basically you're at the mercy of whatever buffering is happening in the output side of the child process.

Upvotes: 0

JTMon
JTMon

Reputation: 3199

I have used a similar setup many times over but can not find a working copy right now :( My first instinct though is to move the line where you initialise the reader (result variable) to before the one where you send the command out to the process (input.println(message)).

Upvotes: 0

Related Questions