简体   繁体   中英

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.

I found this answer on Ant's website (you can remove the "excludes" part to copy the .java sources along the compiled versions):

...
<target name="compile">
    <mkdir dir="${classes.dir}"/>
    <javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/>
    <copy todir="${classes.dir}">
        <fileset dir="${src.dir}" excludes="**/*.java"/>
    </copy>
</target>
...

This copies all resources (as long as they haven't the suffix ".java") to the build directory, so we could start the application from that directory and these files will included into the jar.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM