【发布时间】:2017-01-21 05:27:07
【问题描述】:
我正在从 java 对 linux 文件执行 grep 命令。对于以下代码,它总是返回 null。
Process p;
String matchStr="testmatch";
String output = null;
try {
String command = "grep \""+matchStr+"\" "+ filename;
System.out.println("Running command: " + command);
p = Runtime.getRuntime().exec(command);
System.out.println("***********************************");
System.out.println("***********************************");
System.out.println("***********************************");
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (br.readLine() != null) {
System.out.println("in while loop");
System.out.println("in while loop");
System.out.println("in while loop");
System.out.println(output);
System.out.println("***********************************");
System.out.println("***********************************");
System.out.println("***********************************");
System.out.println("***********************************");
// Process your output here
}
System.out.println("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
如果我直接 grep 它会显示输出,但从 java 它永远不会进入 while 循环。 请在这里提出问题。
【问题讨论】:
-
您是否提供了要搜索的文件的完整路径?
filename有完整的变量路径吗? -
@Inian 是的,它是文件的完整路径。它在读取文件时也没有抛出错误。
-
你能根据你的喜好运行 grep 调用显式 shell
sh或bash,例如String[] command = {"/bin/sh", "-c", "grep \""+matchStr+"\" "吗? -
好的,让我试试@Inian
-
@Inian 你能给我举例说明如何在这个命令中添加文件名吗?