I am trying to execute grep command on the linux using the following java code, but I am not able to capture output. I am getting always null in the output
Process p;
String output = null;
try {
String command = "grep searchString filename.txt";
System.out.println("Running command: " + command);
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
if (null != output) {
while ((output = br.readLine()) != null)
System.out.println(output);
}
p.waitFor();
System.out.println("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
How to capture the output? Is there any third party library or some better way to execute the command on linux and capture the output?
if (null != output) {before assigning any value (other thannull) to the variableoutput. Therefore, sinceoutputisnullat this point you never invokereadLine. If you use an IDE like Eclipse it will tell you something like “this variable can only benullat this point” at youifstatement…