【问题标题】:Referencing Ant build.xml within JAR在 JAR 中引用 Ant build.xml
【发布时间】:2014-04-26 01:49:57
【问题描述】:

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

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 的根目录中。

【问题讨论】:

    标签: java ant jar


    【解决方案1】:

    好吧,令人失望的是,我从来没有完全弄清楚这一点。但是,您可以执行以下操作:

    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
                }
    
            }
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-24
      • 2011-12-27
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 2016-03-13
      • 2014-06-01
      • 1970-01-01
      相关资源
      最近更新 更多