Java执行外部命令/程序,获取输出,可能是错误流,也可能是标准输出流,可以根据需要区分开来输出,我目前是混在一起输出了,
private static String executeCommand() {
StringBuilder sb = new StringBuilder();
try {
Process proc = Runtime.getRuntime().exec("java -version");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// Read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
sb.append(s).append("\n");
}
// Read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
sb.append(s).append("\n");
}
} catch (Exception e) {
sb.append(e.getMessage());
}
return sb.toString().trim();
}
另外发现执行管道命令或者重定向命令的时候,提示无法执行,例如执行 ps aux|grep java echo 'hello'>/opt/test.txt
可以修改如下解决
Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "ps aux|grep java"});
Python下执行外部命令并获得输出,请看:https://blog.terrynow.com/2021/06/07/python-exec-command-and-get-output/
文章评论