41

I use ant for creating .jar files in Eclipse.

I need to generate jar for my project which also contains source code along with the class file. How do we do it?

Another question: what is a debug jar and how to create it using ant? (have heard about it somewhere and trying to relate them both)

Anand
  • 11,872
  • 10
  • 39
  • 51

2 Answers2

75

I would modify your jar task to include multiple filesets; one for the classes and one for the source files.

<jar destfile="${target.dir}/my-app.jar">
    <fileset dir="${target.dir}/classes" />
    <fileset dir="${src.dir}" includes="**/*.java"/>
</jar>

Packaging should be treated as a separate concern from compiling. This will give you more flexibility. For example, you may want to add other filesets to the jar (e.g. properties files), or you may want to package your sources in a jar file that is separate from your class files.

KevinS
  • 7,715
  • 4
  • 38
  • 56
  • 1
    Great answer, and better than my method. I believe I originally copied my `src` folder into `bin` due to some Google Web Toolkit thing. – Michelle Tilley Feb 26 '11 at 06:01
  • Please could you please help me build a jar from this source code github.com/upictec/org.json.me I tried lots of things and even installed maven, but I can't get the jar – eddy May 24 '14 at 13:11
4

Simply copy the source files into the directory you're using for your jar creation. I've done it like this (notice the copy inside compile):

<?xml version="1.0" encoding="utf-8" ?>
<project name="project" default="jar" basedir=".">

    <target name="compile" description="Compile source">
        <mkdir dir="bin" />
        <javac srcdir="src" includes="**" destdir="bin" (other compilation stuff here) />
        <copy todir="bin">
            <fileset dir="src" />
        </copy>
    </target>

    <target name="jar" description="Package into JAR" depends="compile">
        <jar destfile="project.jar" basedir="bin" compress="true" />
    </target>
</project>
Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • I think you should add source file to bin in target "jar", after create jar file, delete those files (by delete whole folder), it will make project cleaner. – hqt Dec 30 '12 at 09:08
  • 1
    Instead of "bin" I would recommend using "${build.classes.dir}" – Alexey Zimarev Jun 23 '13 at 15:12