从 Java 运行 Grep 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18912630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:16:16  来源:igfitidea点击:

Running Grep command from java

javagrep

提问by Ramu Pasupuleti

I want to run grep command from java.

我想从 java 运行 grep 命令。

Here is what I had tried. Please let me know, why it is not displaying ouput.

这是我尝试过的。请让我知道,为什么它不显示输出。

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

采纳答案by anubhava

You don't need to pipe grep's output to wc -l. Just use grep -clike this:

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

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

Though I must say that doing this right inside Java is much cleaner. Consider code like this:

尽管我必须说在 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();
}

回答by vels4j

You must check for any errors.

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

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