Tuesday, September 22, 2009

HOWTO Create Ant build.xml file from Eclipse Java project

I searched around and couldn't find an easy answer for this, but accidentally found it in Eclipse while doing something else. Basically, I created a simple Java program in Eclipse. I wanted to be able to build the program from the command line with ant, but didn't want to hand create the build.xml file when I knew that Eclipse should be able to generate a basic one for me. I kept looking in the "Project" menu and "New" menu for a way to do it.

Answer: It's in the "Export" menu. If you do Export > General > Ant build file, everything works fine.

Beware: it automatically over-writes any build.xml file that may exist with no warning. Don't make modifications unless you figure out a way to preserve them when things change.

Similar task: if you want to produce a runnable JAR file from your project, you can use Export > Java > Runnable Jar to do so. This can also create a custom Ant build file that automatically packs all the Jar stuff you need. NOTE that one of the things this does is re-pack any dependent Jar files you have into one big jar so you can run it with "java -jar."

If you have additional rules in the file that you would like to include in the generated build.xml, you can make Eclipse automatically import these files.

In the same directory, create "build-custom.xml" with the following lines:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse.ant.import?>
<project default="all" name="Create runnable JARs for everything">
<target name="all" depends="build">
... more stuff ...
</target>
</project>

Then export the build.xml file from Eclipse. It will now include a line
<import file="build-custom.xml">
near the beginning. All rules you define in your custom XML file will appear
as part of the build.xml file. You could now execute "ant all" to invoke your "all" rule from the main command line.

NOTE: I think your filename must start with the word "build....xml" in order for Eclipse to find it.

4 comments:

  1. The file name for custom build does not necessarily starts with "build".

    ReplyDelete
  2. The custom build file *does* seem to need to begin with 'build' - mine didn't work until this was done.

    ReplyDelete
  3. Thanks!

    Is there any way to automatically create an ant file that will RUN a java class, or a JUnit test?

    ReplyDelete
  4. Thanks a lot. I was searching for a good doc that can explain me the things in easy way ,and luckly i got ur blog. Thanks for putting things in a very simple way :)

    ReplyDelete