Java 执行命令行
2018-09-04 本文已影响28人
杰哥长得帅
例如 maven 打包:
File wd = new File("/bin");
Process proc = null;
try {
proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
File dest = new File("/tmp/settings.xml");
File mvn = new File("/tmp/apache-maven-3.5.4/bin/mvn");
if (!mavenFile.exists() || !mavenFile.isDirectory() || !mvn.exists()) {
File maven = new File("/tmp/apache-maven-3.5.4-bin.tar.gz");
out.println("cd /tmp");
out.println("tar zxvf /tmp/apache-maven-3.5.4-bin.tar.gz");
}
out.println("cd " + apiPath); // "/tmp/extension-point-api"
out.println("export M2_HOME=/tmp/apache-maven-3.5.4");
out.println("export PATH=$PATH:$M2_HOME/bin");
out.println("mvn clean deploy --settings=/tmp/settings.xml");
out.println("exit");
try {
String line;
boolean success = false;
while ((line = in.readLine()) != null) {
// 输出,可用来测试是否异步
log.info(line);
if (line.contains("BUILD SUCCESS")) {
success = true;
break;
}
}
if (!success) {
throw new Exception();
}
proc.waitFor();
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new Exception();
} finally {
in.close();
out.close();
proc.destroy();
}
}
ProcessBuilder pb = new ProcessBuilder("/bin/bash");
pb.redirectErrorStream(true);
Process proc = null;
BufferedReader reader = null;
PrintWriter writer = null;
File targetDir = new File(targetPath);
if (!targetDir.exists()) {
targetDir.mkdir();
}
try {
proc = pb.start();
reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
List<String> bashLines = Lists.newArrayList();
bashLines.add("cd " + rootPath);
bashLines.add(mavenHome + "/bin/mvn clean package source:jar assembly:single -DskipTests=true");
bashLines.add("cd target");
bashLines.add("zip " + Constant.ZIP_JAVA_SDK_FILE_NAME + " *.jar ../*.md");
bashLines.add("scp " + Constant.ZIP_JAVA_SDK_FILE_NAME + " " + targetPath);
bashLines.add("exit");
LOG.info("Shell({})", Joiner.on("\n").join(bashLines));
for (String bashLine : bashLines) {
writer.println(bashLine);
}
writer.println();
LOG.info("{}", IOUtils.toString(reader));
LOG.info("Finished packaging with exit code({})", proc.exitValue());
} catch (Exception e) {
LOG.error("", e);
} finally {
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (Exception e) {
LOG.error("", e);
}
if (proc != null) {
proc.destroy();
}
}