我正在尝试使用以下java代码在linux上执行grep命令,但我无法捕获输出。我在输出中总是为空
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();
}
如何捕获输出? 是否有任何第三方库或更好的方法在Linux上执行命令并捕获输出?
答案 0 :(得分:1)
output
。更改您的代码如下:
Process p;
String output = null;
try {
String command = "grep searchString filename.txt";
System.out.println("Running command: " + command);
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((output = br.readLine()) != null) {
System.out.println(output);
// Process your output here
}
System.out.println("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}