// 创建一个ANT项目
Project p = new Project();
// 创建一个默认的监听器,监听项目构建过程中的日志操作
DefaultLogger consoleLogger = new DefaultLogger();
ByteArrayOutputStream baop = new ByteArrayOutputStream();
//将控制台信息写入到字符数组中
System.setOut(new PrintStream(baop));consoleLogger.setErrorPrintStream(System.err);
consoleLogger.setOutputPrintStream(System.out);
consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
p.addBuildListener(consoleLogger);
try {
p.fireBuildStarted();
// 初始化该项目
p.init();
//ProjectHelper2 helper = (ProjectHelper2) ProjectHelper.getProjectHelper(); // 会与eclipse自身插件中的Ant起冲突
// 解析项目的构建文件
helper.parse(p, buildFile);
// 执行项目的某一个目标
p.executeTarget(p.getDefaultTarget());
p.fireBuildFinished(null);
printSuccessMessage(baop);
} catch (BuildException be) {
printErrorMsg(p, baop, be);
} finally {
if (baop != null) {
try {
baop.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void printSuccessMessage(ByteArrayOutputStream baop) {
String string;
try {
string = new String(baop.toByteArray(), "utf-8");
string += "恭喜您,编译成功!";
MessageBoxUtil.confirmWithAsync(string);
try {
baop.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void printErrorMsg(Project p, ByteArrayOutputStream baop, BuildException be) throws IllegalArgumentException {
String string;
try {
string = new String(baop.toByteArray(), "utf-8");
string += "抱歉,编译失败,请重新检查配置";
p.fireBuildFinished(be);
System.out.println(string);
throw new IllegalArgumentException(string);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}