Search code examples
javaantbuild-process

How to copy .java sources to Ant javac destFolder


I know how to use Ant to copy files and folders but what I'm interested in is if, and how, I can have the javac task copy the same sources it's compiling to the output directory.

Basically, it's very similar to the option to include your sources in the jar task.


Solution

  • Why not simply use the copy task, along with the javac one ?

    You can even use ant's macro to define your own copyingjavac task, that performs the two operations, with the only problem to correctly handle filesets, to copy exactly the set of files being compiled.

    If you want to only copy a file when compilation succeeded, you will have to either build a custom ant task (extending the default javac task), or to play with ant_contrib foreach task.

    The macrodef could look like:

    <macrodef name="copyingjavac">
      <attribute name="srcdir"/>
      <attribute name="destdir""/>
      <element name="arginclude"/>
      <sequential>
        <javac srcdir="@{srcdir}" destdir="@{destdir}" updatedProperty="build.success">
           <arginclude/>
        </javac>
        <copy todir="@{destdir}">
          <fileset dir="@{srcdir}">
            <arginclude/>
          </fileset>
        </copy>
        <fail unless="build.success">
          Build failed. Check the output...
        </fail>
      </sequential>
    </macrodef>