参考以下实现方式
public static String runLinuxCommand(String command) {
LOG.info("runLinuxCommand command: {}", command);
Process ps = null;
BufferedReader bufIn = null;
BufferedReader bufError = null;
try {
ps = Runtime.getRuntime().exec(command);
ps.waitFor();
bufIn = new BufferedReader(new InputStreamReader(ps.getInputStream(), "utf-8"));
bufError = new BufferedReader(new InputStreamReader(ps.getErrorStream(), "utf-8"));
// 读取输出 result是shell中的输出
StringBuilder result = new StringBuilder();
String line;
while ((line = bufIn.readLine()) != null || (line = bufError.readLine()) != null) {
result.append(line);
}
LOG.info("runLinuxCommand result: {}", result);
return result.toString();
} catch (Exception e) {
LOG.error("runLinuxCommand error", e);
return e.getMessage();
} finally {
close(bufError);
close(bufIn);
ps.destroy();
}
}
private static void close(Closeable closeable) {
if (null != closeable) {
try {
closeable.close();
} catch (IOException e) {
LOG.error("close closeable obj error", e);
}
}
}