我知道您可以使用以下命令在java中运行linux命令并从您刚刚运行的命令中获取输出。
Process p = Runtime.getRuntime().exec("host -t a " + domain);
p.waitFor();
StringBuffer sb = new StringBuffer();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
sb.append(line + "\n");
}
我想知道,有没有更简单的方法从运行的命令获取输出?
答案 0 :(得分:1)
这是我使用的代码。它
private static String run(String... cmds) throws IOException {
ProcessBuilder pb = new ProcessBuilder(cmds);
pb.redirectErrorStream(true);
Process process = pb.start();
StringWriter sw = new StringWriter();
char[] chars = new char[1024];
try (Reader r = new InputStreamReader(process.getInputStream())) {
for (int len; (len = r.read(chars)) > 0; ) {
sw.write(chars, 0, len);
}
}
return sw.toString();
}