1

i want to pass the value from build.xml file to java class at run time. We know that we can pass value from command line with ant to the build.xml file. But how to pass this value from build file to java file. We can done it with property file but how?

Dinesh
  • 86
  • 1
  • 10

2 Answers2

2
  • Use the PropertyFile task to manipulate a properties file from ant.
  • Copy that file to your classpath
  • Use getClass().getClassLoader().getResourceAsStream() to open an input stream to the properties file.
  • Pass that InputStream to Properties.load() to load the properties in your app.
andypandy
  • 1,117
  • 7
  • 9
0

assume you want to read <property name="version" value="123"/> from build.xml, here is plain xml read/parse approach

@Test
public void test_read_build_xml() {
    String buildVersion = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new File("build.xml"));
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("/project/property[@name='version']/@value");
        NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        buildVersion = nodes.item(0).getNodeValue();
    } catch (Exception ex) {
        logger.error("cannot read build version");
    }
    logger.info("buildVersion: " + buildVersion);
    assertNotNull(buildVersion);
}

you can also user Project, ProjectHelper - see How to parse and interpret ant's build.xml

if you want to modify source code from ant, see Is it possible to modify source code with ant?

Sasha Bond
  • 984
  • 10
  • 13