public class ShUtils {
public static ShResult runCommands(List commands) {
System.out.println("执行命令:" + commands.toString());
ShResult result = new ShResult();
String successMsg = null;
String errorMsg = null;
InputStream successIn = null;
InputStream errorIn = null;
try {
ProcessBuilder builder = new ProcessBuilder(commands);
Process process = builder.start();
successIn = process.getInputStream();
errorIn = process.getErrorStream();
successMsg = ShUtils.readInputStream(successIn);
errorMsg = ShUtils.readInputStream(errorIn);
if (successMsg != null && successMsg.length() > 0) {
result.setSuccess(true);
result.setSuccessMsg(successMsg);
}
if (errorMsg != null && errorMsg.length() > 0) {
result.setSuccess(false);
result.setErrorMsg(errorMsg);
return result;
}
System.out.println("ShUtils.runCommands: " + result);
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (successIn != null) {
successIn.close();
}
if (errorIn != null) {
errorIn.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String readInputStream(InputStream in) {
StringBuffer content = new StringBuffer();
int len = -1;
byte[] bs = new byte[4096];
try {
while ((len = in.read(bs)) != -1) {
content.append(new String(bs, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return content.toString();
}
public static class ShResult {
private boolean success;
private String successMsg;
private String errorMsg;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getSuccessMsg() {
return successMsg;
}
public void setSuccessMsg(String successMsg) {
this.successMsg = successMsg;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
@Override
public String toString() {
return "ShResult{" +
"success=" + success +
", successMsg='" + successMsg + ''' +
", errorMsg='" + errorMsg + ''' +
'}';
}
}
}
备注
如需指定命名空间啥的请自行查阅资料----ProcessBuilder



