Let's say you want to extract the output of a console application till you've found a certain keyword. If you have found the keyword the started console process still should be running, however the function which has found the keyword should return.
Here is a minimal application which simply creates an output of n lines (n is the first argument).
LineOutput.java
public class LineOutput {
public static void main(String[] args) {
int iterations = 10;
if (args.length > 0) {
iterations = Integer.valueOf(args[0]);
}
for (int i=0; i < iterations; i++) {
System.out.println("Line " + i);
}
}
}
And here is the main application with the readStreamUntilFound method, which returns as soon as the keyword was found:
ReadTest.java
package org.test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class ReadTest {
public static void main(String[] args) {
System.out.println("Result " + readStreamUntilFound(Arrays.asList("java", "-jar", "test.jar", "10000"), "Line 99"));
}
public static boolean readStreamUntilFound(List<String> cmd, String keyword) {
boolean keywordFound = false;
ProcessBuilder pb = new ProcessBuilder();
pb.command(cmd);
pb.redirectErrorStream(true);
Process p;
try {
p = pb.start();
try {
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
BufferedReader r = new BufferedReader(
new InputStreamReader(bis));
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
if (line.equals(keyword)) {
keywordFound = true;
break;
}
}
} finally {
p.getInputStream().close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return keywordFound;
}
}
I know that the InputStream of a started process must be read, otherwise the process might be blocked. Therefore I am wondering if it is problematic to close the InputStream although the console application still is running (especially in the case where a Java Process object is kept as reference).