Jar Task

## Jar

### Description

Jars a set of files.

The basedir attribute is the reference directory from where to jar.

Note that file permissions will not be stored in the resulting jarfile.

It is possible to refine the set of files that are being jarred. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports most attributes of `<fileset>` (dir becomes basedir) as well as the nested `<include>`, `<exclude>` and `<patternset>` elements.

You can also use nested file sets for more flexibility, and specify multiple ones to merge together different trees of files into one JAR. The extended `fileset` and `groupfileset` child elements from the `zip` task are also available in the `jar` task. See the Zip task for more details and examples.

The update parameter controls what happens if the JAR file already exists. When set to yes, the JAR file is updated with the files specified. When set to no (the default) the JAR file is overwritten. An example use of this is provided in the Zip task documentation. Please note that ZIP files store file modification times with a granularity of 2 seconds. If a file is less than 2 seconds newer than the entry in the archive, Ant will not consider it newer.

If the manifest is omitted, a simple one will be supplied by Apache Ant.

The whenmanifestonly parameter controls what happens when no files, apart from the manifest file, or nested services, match. If skip, the JAR is not created and a warning is issued. If fail, the JAR is not created and the build is halted with an error. If create (default), an empty JAR file (only containing a manifest and services) is created.

(The `Jar` task has a shortcut for specifying the manifest file of a JAR file. The same thing can be accomplished by using the fullpath attribute of a `zipfileset` in a `Zip` task. The one difference is that if the manifest attribute is not specified, the `Jar` task will include an empty one for you.)

Manifests are processed by the `Jar` task according to the Jar file specification. Note in particular that this may result in manifest lines greater than 72 bytes being wrapped and continued on the next line.

The `Jar` task checks whether you specified package information according to the versioning specification.

Please note that the ZIP format allows multiple files of the same fully-qualified name to exist within a single archive. This has been documented as causing various problems for unsuspecting users. If you wish to avoid this behavior you must set the duplicate attribute to a value other than its default, add.

To cryptographically sign your JAR file, use the SignJar task on the JAR that you create from this task.

For creating a simple version of a JEP 238 multi-release jar, you don't need any special tools. Just set the required `manifest` entry and place the files where required, as you could see in the JEP 238 example. If you want to tune this kind of jar, e.g. decreasing the size by deleting 'same' classes from the versions-branches, you have to do more ...

### Parameters

Attribute | Description | Required
--- | --- | ---
destfile | the JAR file to create. | Yes
basedir | the directory from which to jar the files. | No
compress | Not only store data but also compress them. Unless you set the keepcompression attribute to false, this will apply to the entire archive, not only the files you've added while updating. | No; defaults to true
keepcompression | For entries coming from existing archives (like nested `zipfileset`s or while updating the archive), keep the compression as it has been originally instead of using the compress attribute. Since Ant 1.6 | No; defaults to false
encoding | The character encoding to use for filenames inside the archive. It is not recommended to change this value as the created archive will most likely be unreadable for Java otherwise. See also the discussion in the zip task page | No; defaults to UTF8
filesonly | Store only file entries | No; defaults to false
includes | comma- or space-separated list of patterns of files that must be included | No; defaults to all (**)
includesfile | name of a file. Each line of this file is taken to be an include pattern | No
excludes | comma- or space-separated list of patterns of files that must be excluded | No; defaults to default excludes or none if defaultexcludes is no
excludesfile | Name of a file. Each line of this file is taken to be an exclude pattern | No
defaultexcludes | indicates whether default excludes should be used or not (yes|no) | No; defaults to yes
manifest | the manifest file to use. This can be either the location of a manifest, or the name of a jar added through a fileset. If its the name of an added jar, the task expects the manifest to be in the jar at `META-INF/MANIFEST.MF` | No
filesetmanifest | behavior when a manifest is found in a `zipfileset` or `zipgroupfileset` file. Valid values are skip, merge, and mergewithoutmain. merge will merge all of the manifests together, and merge this into any other specified manifests. mergewithoutmain merges everything but the Main section of the manifests. | No; defaults to skip
update | indicates whether to update or overwrite the destination file if it already exists | No; defaults to false
whenmanifestonly | behavior when no files match. Valid values are fail, skip, and create. | No; defaults to create
duplicate | behavior when a duplicate file is found. Valid values are add, preserve, and fail. | No; defaults to add
index | whether to create an index list to speed up classloading. This is a JDK 1.3+ specific feature. Unless you specify additional jars with nested `indexjars` elements, only the contents of this jar will be included in the index. | No; defaults to false
indexMetaInf | whether to include `META-INF` and its children in the index. Doesn't have any effect if index is false. Sun's jar implementation used to skip the `META-INF` directory and Ant followed that example. The behavior has been changed with Java 5. In order to avoid problems with Ant generated jars on Java 1.4 or earlier Ant will not include `META-INF` unless explicitly asked to. Since Ant 1.8.0 | No; defaults to false
manifestencoding | The encoding used to read the JAR manifest, when a manifest file is specified. The task will always use UTF-8 when writing the manifest. | No; defaults to default JVM character encoding
roundup | Whether the file modification times will be rounded up to the next even number of seconds. Zip archives store file modification times with a granularity of 2 seconds, so the times will either be rounded up or down. If you round down, the archive will always seem out-of-date when you rerun the task, so the default is to round up. Rounding up may lead to a different type of problems like JSPs inside a web archive that seem to be slightly more recent than precompiled pages, rendering precompilation useless. Since Ant 1.6.2 | No; defaults to true
level | Non-default level at which file compression should be performed. Valid values range from 0 (no compression/fastest) to 9 (maximum compression/slowest). Since Ant 1.7 | No
strict | Configures how to handle breaks of the packaging version specification: fail = throws a BuildException warn = logs a message on warn level ignore = logs a message on verbose level (default) Since Ant 1.7.1 | No; defaults to ignore
preserve0permissions | when updating an archive or adding entries from a different archive Ant will assume that a Unix permissions value of 0 (nobody is allowed to do anything to the file/directory) means that the permissions haven't been stored at all rather than real permissions and will instead apply its own default values. Set this attribute to true if you really want to preserve the original permission field. since Ant 1.8.0 | No; defaults to false
useLanguageEncodingFlag | Whether to set the language encoding flag if the encoding is UTF-8. This setting doesn't have any effect if the encoding is not UTF-8. Since Ant 1.8.0. See also the discussion in the zip task page | No; defaults to true
createUnicodeExtraFields | Whether to create Unicode extra fields to store the file names a second time inside the entry's metadata. Possible values are never, always and not-encodeable which will only add Unicode extra fields if the file name cannot. See also the discussion in the zip task page | No; defaults to never
fallbacktoUTF8 | Whether to use UTF-8 and the language encoding flag instead of the specified encoding if a file name cannot be encoded using the specified encoding. Since Ant 1.8.0. See also the discussion in the zip task page | No; defaults to false
mergeClassPathAttributes | Whether to merge the `Class-Path` attributes found in different manifests (if merging manifests). If false, only the attribute of the last merged manifest will be preserved. Since Ant 1.8.0. Unless you also set flattenAttributes to true, this may result in manifests containing multiple `Class-Path` attributes which violates the manifest specification. | No; defaults to false
flattenAttributes | Whether to merge attributes occurring more than once in a section (this can only happen for the `Class-Path` attribute) into a single attribute. Since Ant 1.8.0. | No; defaults to false
zip64Mode | When to use Zip64 extensions for entries. The possible values are never, always and as-needed. Since Ant 1.9.1. See also the discussion in the zip task page | No; defaults to never

### Parameters specified as nested elements

#### metainf

The nested `metainf` element specifies a FileSet. All files included in this fileset will end up in the `META-INF` directory of the jar file. If this fileset includes a file named `MANIFEST.MF`, the file is ignored and you will get a warning.

#### manifest

The nested `manifest` element allows the manifest for the Jar file to be provided inline in the build file rather than in an external file. This element is identical to the manifest task, but the file and mode attributes must be omitted.

If both an inline manifest and an external file are both specified, the manifests are merged.

When using inline manifests, the `Jar` task will check whether the manifest contents have changed (i.e. the manifest as specified is different in any way from the manifest that exists in the jar, if it exists. If the manifest values have changed, the jar will be updated or rebuilt, as appropriate.

#### indexjars

Since Ant 1.6.2

The nested `indexjars` element specifies a path-like structure. Its content is completely ignored unless you set the index attribute of the task to true.

The index created by this task will contain indices for the archives contained in this path, the names used for the archives depend on your manifest:

- If the generated jar's manifest contains no `Class-Path` attribute, the file name without any leading directory path will be used and all parts of the path will get indexed.
- If the manifest contains a `Class-Path` attribute, this task will try to guess which part of the `Class-Path` belongs to a given archive. If it cannot guess a name, the archive will be skipped, otherwise the name listed inside the `Class-Path` attribute will be used.

This task will not create any index entries for archives that are empty or only contain files inside the `META-INF` directory unless the indexmetainf attribute has been set to true.

#### service

Since Ant 1.7.0

The nested `service` element specifies a service. Services are described in the service provider overview. The approach is to have providers JARs include files named by the service provided, for example, `META-INF/services/javax.script.ScriptEngineFactory` which can include implementation class names, one per line (usually just one per JAR).

The name of the service is set by the type attribute. The classname implementing the service is the the provider attribute, or if one wants to specify a number of classes that implement the service, by `provider` nested elements.

Attribute | Description | Required
--- | --- | ---
type | The name of the service. | Yes
provider | The classname of the class implementing the service. | Yes, unless there is a nested `<provider>` element.

The provider classname is specified either by the provider attribute, or by a nested `<provider>` element, which has a single classname attribute. If a JAR file has more that one implementation of the service, a number of nested `<provider>` elements may be used.

### Examples

#### Simple

Jar all files in the `${build}/classes` directory into a file called `app.jar` in the `${dist}/lib` directory.

    <jar destfile="${dist}/lib/app.jar" basedir="${build}/classes"/>

#### With filters

Jar all files in the `${build}/classes` directory into a file called `app.jar` in the `${dist}/lib` directory. Files with the name `Test.class` are excluded.

    <jar destfile="${dist}/lib/app.jar"
         basedir="${build}/classes"
         excludes="**/Test.class"/>

Jar all files in the `${build}/classes` directory into a file called `app.jar` in the `${dist}/lib` directory. Only files under the directory `mypackage/test` are used, and files with the name `Test.class` are excluded.

    <jar destfile="${dist}/lib/app.jar"
         basedir="${build}/classes"
         includes="mypackage/test/**"
         excludes="**/Test.class"/>

#### Multiple filesets

Jar all files in the `${build}/classes` directory and also in the `${src}/resources` directory together into a file called `app.jar` in the `${dist}/lib` directory. Files with the name `Test.class` are excluded. If there are files such as `${build}/classes/mypackage/MyClass.class` and `${src}/resources/mypackage/image.gif`, they will appear in the same directory in the jar (and thus be considered in the same package by Java).

    <jar destfile="${dist}/lib/app.jar">
        <fileset dir="${build}/classes"
                 excludes="**/Test.class"/>
        <fileset dir="${src}/resources"/>
    </jar>

#### Merging archives

Create an executable jar file with a main class `com.acme.checksites.Main`, and embed all the classes from the jar `lib/main/some.jar`.

    <jar destfile="build/main/checksites.jar">
        <fileset dir="build/main/classes"/>
        <zipfileset includes="**/*.class" src="lib/main/some.jar"/>
        <manifest>
          <attribute name="Main-Class"
                     value="com.acme.checksites.Main"/>
        </manifest>
    </jar>

Create an executable jar file with a main class `com.acme.checksites.Main`, and embed all the classes from all the jars in `lib/main`.

    <jar destfile="build/main/checksites.jar">
        <fileset dir="build/main/classes"/>
        <restrict>
           <name name="**/*.class"/>
           <archives>
               <zips>
                   <fileset dir="lib/main" includes="**/*.jar"/>
               </zips>
           </archives>
        </restrict>
        <manifest>
            <attribute name="Main-Class"
                  value="com.acme.checksites.Main"/>
        </manifest>
    </jar>

#### Inline manifest

    <jar destfile="test.jar" basedir=".">
        <include name="build"/>
        <manifest>
            <!-- If this is an Applet or Web Start application, include
                 the proper attributes from https://docs.oracle.com/javase/8/docs/technotes/guides/jweb/index.html -->
            <attribute name="Permissions" value="sandbox"/>
            <attribute name="Codebase" value="example.com"/>
            <!-- Who is building this jar? -->
            <attribute name="Built-By" value="${user.name}"/>
            <!-- Information about the program itself -->
            <attribute name="Implementation-Vendor" value="ACME inc."/>
            <attribute name="Implementation-Title" value="GreatProduct"/>
            <attribute name="Implementation-Version" value="1.0.0beta2"/>
            <!-- details -->
            <section name="common/MyClass.class">
                <attribute name="Sealed" value="false"/>
            </section>
        </manifest>
    </jar>

This is an example of an inline manifest specification including the version of the build program (`Implementation-Version`). Note that the `Built-By` attribute will take the value of the Ant property `user.name`. The manifest produced by the above would look like this:

    Manifest-Version: 1.0
    Permissions: sandbox
    Codebase: example.com
    Built-By: conor
    Implementation-Vendor: ACME inc.
    Implementation-Title: GreatProduct
    Implementation-Version: 1.0.0beta2
    Created-By: Apache Ant 1.9.2

    Name: common/MyClass.class
    Sealed: false

#### Service Provider

The following shows how to create a jar file specifying a service with an implementation of the JDK 6 scripting interface:

    <jar destfile="pinky.jar">
        <fileset dir="build/classes"/>
        <service type="javax.script.ScriptEngineFactory"
                 provider="org.acme.PinkyLanguage"/>
    </jar>

The following shows how to create a jar file specifying a service with two implementations of the JDK 6 scripting interface:

    <jar destfile="pinkyandbrain.jar">
        <fileset dir="classes"/>
        <service type="javax.script.ScriptEngineFactory">
            <provider classname="org.acme.PinkyLanguage"/>
            <provider classname="org.acme.BrainLanguage"/>
        </service>
    </jar>

#### JEP 238 example: a Multi-Release JAR Files

Here we want to create a Multi-Release JAR File according the specification JEP 238. It defines on top of a JAR the possibility to place additional or overwriting classes in a jar, which are available according to the Java version you run.
Basically it says, that you have to set the manifest entry `Multi-Release: true` and place all additional or overwriting classes in `META-INF/versions/number/package-structure`, e.g. `META-INF/versions/9/org/apache/ant/MyClass.class`

In this example we expect that the normal classes are compiled into `${java.classes}` and the Java 9 classes are compiled into `${java9.classes}`.

    <jar destfile="mrjar.jar">
        <manifest>
            <!-- special mf-entry according to the spec -->
            <attribute name="Multi-Release" value="true"/>
        </manifest>
        <!-- directory structure according to the spec ... -->
        <!-- ... default classes loadable by old (<Java 9) versions -->
        <fileset dir="${java.classes}"/>
        <!-- ... per release classes, require Java 9+ for loadable via standard ClassLoader -->
        <zipfileset prefix="META-INF/versions/9/" dir="${java9.classes}"/>
    </jar>