java代码内调用shell命令:
Runtime.getRuntime().exec(String[] command);
// command 是一个三个元素数组 一:命令位置;二:-c表示先执行第一个参数;三:你的命令。
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", cmd });
} catch (IOException ioException) {
ioException.printStackTrace();
}
if (process == null) {
log.error("execute shell command faild, command is [{}]", cmd);
return "";
}
将process 用Callable封装
private static class ShellCallable implements Callable<String> {
private Process process;
ShellCallable(Process process) {
this.process = process;
}
@Override
public String call() throws Exception {
InputStream input = process.getInputStream();
String result = getResult(input).trim();
if (result.equals("")) {
InputStream error = process.getErrorStream();
String errorInfo = getResult(error);
if (!errorInfo.equals("")) {
log.error("shell command execute faild, error info is [{}]", errorInfo.trim());
}
}
return result;
}
private String getResult(InputStream input) throws Exception {
byte[] buffer = new byte[1024];
StringBuffer answer = new StringBuffer();
int len = -1;
while (true) {
len = input.read(buffer);
if (len == -1) {
break;
}
String str = new String(buffer, 0, len);
answer.append(str);
}
return answer.toString();
}
}
Future<String> future = pool.submit(new ShellCallable(process));
参考: https://blog.csdn.net/margin_0px/article/details/83822275
网友评论