繁体   English   中英

从java运行Grep命令

[英]Running Grep command from java

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

您不需要将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();
}

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

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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM