如何通过Java代码运行命令

时间:2017-11-27 09:21:49

标签: java linux grep command

我想通过Java代码执行以下命令。任何人都可以建议我如何执行它?

找到./path/ | grep“keyword”| grep -rnw -e“keyword”

我在尝试很多方面,但没有得到正确的输出。

1 个答案:

答案 0 :(得分:0)

Runtime.getRuntime().exec()是你的朋友。

他们是对的,它是少数其他问题的重复,但主要是这一个:How to make pipes work with Runtime.exec()?

此处更好地涵盖了打印出来的答案: java runtime.getruntime() getting output from executing a command line program

好像你想通过java代码执行管道。我发现使用shell或bash最简单。如果可以的话,你也可以探索org.apache.commons.exec包。

我将如何做到这一点:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

    public static void main(String argv[]) {
        try {
            String[] cmd = {
                    "/bin/sh",
                    "-c",
                    "find ./path/ | grep \"keyword\" | grep -rnw -e \"keyword\""
            };

            Process exec = Runtime.getRuntime().exec(cmd);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(exec.getErrorStream()));

            System.out.println("Standard output:\n");
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

            System.out.println("Error output:\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
相关问题