在JAR中引用Ant build.xml

时间:2014-04-23 01:25:52

标签: java ant jar

我正在使用Java代码通过可执行jar执行ANT任务。我想在可执行的JAR中包含build.xml,但无法弄清楚如何在我的代码中引用它。任何帮助表示赞赏。

public static void main(String[] args) {
    BuildLogger logger = new DefaultLogger();
    logger.setMessageOutputLevel(Project.MSG_INFO);
    logger.setOutputPrintStream(System.out);
    logger.setErrorPrintStream(System.out);
    logger.setEmacsMode(true);

    ProjectHelper ph = ProjectHelper.getProjectHelper();
    Project p = new Project();
    p.addBuildListener(logger);
    p.init();
    p.addReference("ant.projectHelper", ph);
    //File f = new File(this.getClass().getResource("/report.xml").toURI()); I can't do toURI on this, it throws an exception
    ph.parse(p, this.getClass().getResource("/report.xml")); //This throws a NullPointerException within ANT
    p.executeTarget("dumpandreport");
}

如果我创建一个引用外部build.xml文件的java.io.File对象并在ph.parse中指定它,则可行...如果我尝试引用在JAR中打包的文件,这不。我已经验证(通过7-ZIP)文件report.xml实际上是在JAR的根目录中。

1 个答案:

答案 0 :(得分:0)

嗯,令人失望的是,我从来没有想过这个。但是,您可以执行以下操作:

public static void main(String[] args) {
    ...
    ph.parse(p, getAntXML()};
    ...
}

private Object getAntXML() throws IOException {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        inputStream = this.getClass().getResourceAsStream("/report.xml");
        File f = File.createTempFile("report", "xml");
        outputStream = new FileOutputStream(f);
        int read;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        return f;
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                //Nop
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                //Nop
            }

        }
    }
}

无论如何,这对我的目的来说已经足够好了。