O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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>

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required