Stuff Stuff in JARs #85
Chapter 11, Native Integration and Packaging
Granted, this is all pretty burdensome if you have to do it over and over.
Presumably, you’ll want to automate creating and populating your JAR, and
the most popular way to do that is with Apache Ant (http://ant.apache.org/).
Ant lets you split up and customize the compiling and JAR-building tasks,
and its XML syntax is far easier to read than command-line options.
Example 11-8 shows a simple Ant build.xml file that builds this example and
packs it into a JAR, along with a Manifest file that specifies the main class.
Because the default target (
all) runs the compile and package targets as
needed, to compile the application and stuff it and its resources into a JAR,
use the command:
And the Kitchen Sink
Because you can get a URL and thus an InputStream—via URL.openStream( )—
from any resource found in a JAR, you can put pretty much any kind of file
into the JAR and read it back at runtime. This example used images and
sounds for simplicity, since
ImageIcon’s constructor and AudioSystem.
both take URL objects directly, but if you’re willing to
deal with reading the stream yourself, there’s no reason you couldn’t put
other kinds of files in the JAR. You could put a properties file with default
settings in the JAR, open a stream, and then read it into a
load( ) method. You could put an executable in the JAR and extract
it to the local filesystem. You could even put a ZIP file in the JAR, add code
to open the ZIP and decompress it to disk, and thus have a self-extracting
Example 11-8. Ant file to compile an application and build a JAR file
<project name="jar-resource-loading" default="all" basedir=".">
<javac srcdir="." destdir="."/>
includes="*.class, images/*, sounds/*"
<target name="all" depends="compile, package" />