3

我想从 java 运行 grep 命令。

这是我尝试过的。请告诉我,为什么它不显示输出。

public static void main(String args[]) throws IOException{
    Runtime rt = Runtime.getRuntime();
    String[] cmd = { "/bin/sh", "-c", "grep 'Report Process started' server.log|wc -l" };
    Process proc = rt.exec(cmd);
    BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line;
    while ((line = is.readLine()) != null) {
        System.out.println(line);
    }
    System.out.println("Done");
}
4

2 回答 2

2

您不需要将 grep 的输出通过管道传输到wc -l. 像这样使用grep -c

String[] cmd = {"/bin/sh", "-c", "grep -c 'Report Process started' /path/to/server.log"};

虽然我必须说在 Java 中这样做会更干净。考虑这样的代码:

String logdata = new Scanner(new File("/path/to/server.log")).useDelimiter("\\Z").next();
final String needle = "Report Process started";
int occurrences = 0;
int index = 0;
while (index < logdata.length() && (index = logdata.indexOf(needle, index)) >= 0) {
    occurrences++;
    index += needle.length();
}
于 2013-09-20T09:04:49.277 回答
2

您必须检查是否有任何错误。

private static void printStream(InputStream in) throws IOException {
    BufferedReader is = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = is.readLine()) != null) {
            System.out.println(line);
        }
}
public static void main(String args[]) {
    try {
        Runtime rt = Runtime.getRuntime();
        String[] cmd = {"/bin/sh", "-c", "grep 'Report Process started' server.log|wc -l"};
        Process proc = rt.exec(cmd);
        printStream(proc.getInputStream());
        System.out.println("Error : ");
        printStream(proc.getErrorStream());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
于 2013-09-20T09:08:12.210 回答