java - 如何通过Java代码运行命令

标签 java linux grep command

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

查找./路径/| grep "关键字"| grep -rnw -e "关键字"

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

最佳答案

Runtime.getRuntime().exec() 是你的 friend 。

伙计们是对的,这是其他几个问题的重复,但主要是这个: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();
        }
    }
}

关于java - 如何通过Java代码运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47507452/

相关文章:

linux - 识别不包含具有特定字符串的文件的文件夹

linux - 为重复命令创建自定义 Linux 命令

java - 有没有办法改变 Spark 中 RDD 的复制因子?

java - JLabels 的鼠标监听器

linux - sed:只是试图删除一个子字符串

javascript - 我可以从 javascript 生成的网页中获取结果吗

regex - 在 bash 中用空格分隔一个完整的单词

Java:在链接列表中挑选多个元素

java - Spring Validation - 如何在我的 Controller 中检索 errors.rejectValue?

c - FIFO channel 读取不正确