I got a process which runs under unix (shell-script). This script runs continuously and generates more output every second.
Now I tried to get the current output of it using the BufferedReader in Java. Now I realized that this one is waiting for the process to complete, so it’s waiting forever.
How can I realize this otherwise? I just want to get the current output of a Process p as a String.
What I got until now:
Process p = Runtime.getRuntime().exec("./myScript.sh");
InputStream stdin = p.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String returner = "";
String line = null;
try {
while ( (line = br.readLine()) != null) {
returner += line;
}
}
catch (IOException e) {
System.err.println( "Processhandling went terribly wrong!");
System.exit(1);
}
Thank you for your help
Regards, Flo
You are appending each line you read onto an existing String.
Firstly, appending Strings like this is inefficient – you should use a StringBuilder, especially for large or numerous strings. Your method will get slower and slower (and eventually fill up all memory).
You keep appending forever (as long as there is input data), so as you say, it never completes.
You need to read a chunk of data (maybe a line at a time, but it depends on your data) and then process that chunk (possibly in another thread so that reading and processing can occur in parallel).
So instead of:
You need:
Where
processLine()does something useful with the data.