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?
Asked
Active
Viewed 1,824 times
1
-
1How will you invoke said Java class? Inside ant or later? – Thorbjørn Ravn Andersen Oct 19 '11 at 06:38
-
1maybe this helps: http://stackoverflow.com/questions/3730880/use-ant-for-running-program-with-command-line-arguments – raven Oct 19 '11 at 06:48
-
java class is invoked by ant build file using testNg. – Dinesh Oct 19 '11 at 07:40
-
You need to be more specific. Do you want Ant to modify your source code (a .java file), or do you want to access a value (of a property?) generated by Ant while your program runs? – MaDa Oct 19 '11 at 08:03
-
ya i want to modify the a.java file – Dinesh Oct 19 '11 at 08:18
2 Answers
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