/**
* 用java执行命令行
* @param cmdList 要执行的命令
* @param workDir 执行的工作目录,建议就是执行文件的目录
*/
private void performCommand(List<String> cmdList, String workDir){
final ProcessBuilder builder = new ProcessBuilder((String[]) cmdList.toArray(new String[cmdList.size()]));
builder.directory(new File(workDir));
Thread thread = new Thread(new Runnable() {
public void run() {
try {
final Process process = builder.start();
final AtomicBoolean programDestroy = new AtomicBoolean(false);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
programDestroy.compareAndSet(false, true);
process.destroy();
}
});
int exitCode = process.waitFor();
if (exitCode != 0 && !programDestroy.get()) {
// to do 改为log记录
System.out.println("Unexpected error occur at filebeat exit, code={}" + exitCode);
}
} catch (IOException var5) {
// to do 改为log记录
System.out.println("Unexpected error occur at filebeat startup" + var5);
} catch (InterruptedException var6) {
// ignore
}
}
});
thread.start();
}
// 执行java -jar
@Test
public void testSyntaxError() throws IOException {
List<String> cmdList = new ArrayList();
cmdList.add("java");
cmdList.add("-jar");
cmdList.add("echo-server.jar");
performCommand(cmdList, "D:\\bingo");
}
网友评论