因某些情况下需要调用Java程序执行Linux命令,过程中有写坑,记录下:
@Slf4j
public class CommandUtil {
public static Result<Boolean> run(List<String> commandArr){
File wd = new File("/bin");
Process proc = null;
try {
proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
} catch (IOException e) {
log.error("CommandUtil.run IOException",e);
return CommonError.SERVICE_ERROR.toResult(e.getLocalizedMessage());
}
if (proc != null) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true)) {
for (String command : commandArr) {
out.println(command);
}
out.println("echo ready exit");
out.println("exit");
String result;
while ((result = in.readLine()) != null) {
log.info("command exec result:{}", result);
}
} catch (Exception e) {
log.error("CommandUtil.run Exception", e);
return CommonError.SERVICE_ERROR.toResult(e.getLocalizedMessage());
} finally {
proc.destroy();
}
return Result.successResult(true);
}else {
return CommonError.SERVICE_ERROR.toResult("Process is null");
}
}
}
工具类调用示例:
List<String> commandArr = new ArrayList();
commandArr.add("cd " + projectRootPath);
commandArr.add("pwd");
commandArr.add("cd target/classes");
commandArr.add("pwd");
commandArr.add("jar -cvf " + jarOutPathName + " " + jarClassPathName);
commandArr.add("echo jar update");
commandArr.add("jar -uvf " + jarOutPathName + " " + jarClassPathName);
log.info(JSON.toJSONString(commandArr));
return CommandUtil.run(commandArr);
踩过的坑如下:
上述工具类是打开一个命令行窗口,可执行linux命令cd,用其它方式调用执行cd命令,会出错,异常如下:
java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory