原因:没有读取命令的输出流和错误流,导致缓冲区溢出而阻塞。
工具类封装
package com.oics.common.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ProcessUtils {
public static CommandResult exec(String command) throws IOException, InterruptedException {
Process process = Runtime.getRuntime().exec(command);
StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());
outputGobbler.start();
errorGobbler.start();
int isSuccess = process.waitFor();
outputGobbler.join();
errorGobbler.join();
String output = outputGobbler.getOutput();
String error = errorGobbler.getOutput();
return new CommandResult(isSuccess, output, error);
}
private static class StreamGobbler extends Thread {
private InputStream inputStream;
private StringBuilder outputBuilder;
StreamGobbler(InputStream inputStream) {
this.inputStream = inputStream;
this.outputBuilder = new StringBuilder();
}
public void run() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = reader.readLine()) != null) {
outputBuilder.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String getOutput() {
return outputBuilder.toString();
}
}
public static class CommandResult {
private int isSuccess;
private String output;
private String error;
CommandResult(int isSuccess, String output, String error) {
this.isSuccess = isSuccess;
this.output = output;
this.error = error;
}
public int getIsSuccess() {
return isSuccess;
}
public String getOutput() {
return output;
}
public String getError() {
return error;
}
}
}
// 待执行的命令
String cmd= "docker ps";
ProcessUtils.CommandResult exec = ProcessUtils.exec(cmd);
// 是否成功
int isSuccess = exec.getIsSuccess();
// 错误信息
String error = exec.getError();