views:

3779

answers:

4

I have a project that needs to access resources within its own JAR file. When I create the JAR file for the project, I would like to copy a directory into that JAR file (I guess the ZIP equivalent would be "adding" the directory to the existing ZIP file). I only want the copy to happen after the JAR has been created (and I obviously don't want the copy to happen if I clean and delete the JAR file).

Currently the build file looks like this:

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

    <!-- project-specific properties -->
    <property name="project.path" value="my/project/dir/foobar" />

    <patternset id="project.include">
        <include name="${project.path}/**" />
    </patternset>
    <patternset id="project.jar.include">
        <include name="${project.path}/**" />
    </patternset>

    <import file="common-tasks.xml" />

    <property name="jar.file" location="${test.dir}/foobar.jar" />    
    <property name="manifest.file" location="misc/foobar.manifest" />
</project>

Some of the build tasks are called from another file (common-tasks.xml), which I can't display here.

Thanks.

+2  A: 

One way is to use the Ant Tasks Unzip (to explode the Jar is a temp folder), Copy (to copy the folder that you want to the temp folder), and Jar with update set to true (to package the temp folder back to the original jar file).

The Ant Manual has examples on how to do it.

Handerson
@Handerson: Yeap +1
OscarRyz
I'd like to avoid this method if possible. I've seen a way to do what I want, but I can't recall the details.
Blue
+3  A: 
<jar update="true">
...
</jar>
OscarRyz
I'm not sure what actually goes in the "..."
Blue
http://ant.apache.org/manual/CoreTasks/jar.html
OscarRyz
+2  A: 

The Jar/Ear Ant tasks are subtasks of the more general Zip task. This means that you can also use zipfileset in your Jar task:

<jar destfile="${jar.file}" basedir="...">
    <zipfileset dir="${project.path}" includes="*.jar" prefix="libs"/>
</jar>

I've also seen that you define a separate manifest file for inclusion into the Jar. You can also use a nested manifest command:

<jar destfile="@{destfile}" basedir="@{basedir}">
    <manifest>
        <attribute name="Built-By" value="..."/>
        <attribute name="Built-Date" value="..."/>

        <attribute name="Implementation-Title" value="..."/>
        <attribute name="Implementation-Version" value="..."/>
        <attribute name="Implementation-Vendor" value="..."/>
    </manifest>
</jar>
Vladimir
A: 

Is there a way to get an external file copied into the executable jar through the applets code? It would be great to have a static method or class embedded into jar files that appended to the executable jar as a resulting resource. I imagine the ziptools in the java classes in NetBeans have an append function.

i2programmer