[英]Execute grep command on Linux and capture result
我正在尝试使用以下Java代码在linux上执行grep命令,但无法捕获输出。 我总是在输出中为null
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上执行命令并捕获输出?
如果进行检查,则未分配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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.