【问题标题】:How to run command through Java code [duplicate]如何通过Java代码运行命令[重复]
【发布时间】:2018-05-10 11:40:13
【问题描述】:

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

找到 ./path/ | grep "关键字" | grep -rnw -e "关键字"

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

【问题讨论】:

  • 我们看不到您的代码,因此无法告诉您其中有什么问题。在网上找到这样的例子应该不难。
  • 伙计们,你说这是其他问题的重复,但你只指定了一个重复,它实际上是我想说的其他几个问题的组合。尤其是这里标记的原始问题根本没有谈论管道......在我看来,你有点太快将其标记为重复

标签: java linux grep command


【解决方案1】:

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

【讨论】:

  • 您好 Gralak,感谢您的宝贵回复!我还有一个疑问。我想 grep "somekey="value"" /path/fileName.在命令窗口中,我使用 / (grep "somekey=\"value\"" /path/fileName) 得到了输出。但是从Java,它不起作用..你有什么解决方案吗?
猜你喜欢
  • 2020-02-26
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
相关资源
最近更新 更多