Stuff Stuff in JARs #85
Chapter 11, Native Integration and Packaging
|
433
HACK
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:
ant
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.
getAudioInputStream( )
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
Properties object
via the
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
archive.
Example 11-8. Ant file to compile an application and build a JAR file
<project name="jar-resource-loading" default="all" basedir=".">
<target name="compile">
<javac srcdir="." destdir="."/>
</target>
<target name="package">
<jar destfile="buh.jar"
basedir="."
includes="*.class, images/*, sounds/*"
manifest="manifest.txt" />
</target>
<target name="all" depends="compile, package" />
</project>

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.