从java运行Grep命令

时间:2013-09-20 08:57:10

标签: java grep

我想从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");
}

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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();
    }
}