我想通过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/