Week 11: classpath and packaging in Java
2013-04-02
Jar files are the standard way of packaging Java libraries and programs.
The classpath is the set of directories (or jar files) where Java looks
for libraries and programs to load, similar to the PATH
environment variable
for a shell. The notation used is often similar -- when you specify the
classpath on the command line, you list directories separated by ;
(on
Windows, or :
on other systems), just like PATH
.
Setting the classpath
Both java
and javac
need to know where to look for any libraries that your
program needs to use. The JDK setup should automatically configure those
programs to find all the builtin Java libraries, but not any additional
libraries you might download.
To add directories to the list to search, you can specify an extra -cp
flag each time you run java
or javac
, which looks like this on Windows:
java -cp ".;other\directory;somejarfile.jar" MyClass
Note that .
indicates the current directory, which you probably want to
include to make sure that you can run programs in your current directory.
Alternately, you can set a CLASSPATH
environment variable to add
directories:
set CLASSPATH=.;other\directory;somejarfile.jar
java MyClass
To add a jar file for use in NetBeans, right-click on the libraries section
of your project and choose "Add JAR/Folder":
For large projects, the recommended way to deal with all of this is to have our
build automation tools deal with setting up and/or keeping track of the
classpath for us.
Jar files
Jar files are just zip files with a set of conventions for what the Java runtime
or compiler expect to find inside. The JDK comes with a jar
program
that you can use to create jar files on the command line.
The basic structure inside a jar file is just a file that contains information
about what else is in the jar file called a manifest
, plus all the other
files. Often, all the other files will just be java class files. Here's
the contents of the jar file we created last time, which can be listed
using the command jar tf Hello.jar
:
META-INF/
META-INF/MANIFEST.MF
Hello.class
HelloGUI$1.class
HelloGUI.class
We used ant
to create the jar file, but we could use the jar
program
to build it instead. Running from within the build
directory, use the
following command:
jar cfe Hello.jar HelloGUI *.class
The first argument is always an acronym for the operation to perform. Here,
cfe
stands for create
file
with entrypoint
, and then we specify the
output file, the entrypoint (the class that we run as the main class), and all
the files to package inside Hello.jar.
Readings
This jar file tutorial covers many of the details (what we used plus a
lot more) of working with jar files and the jar
program.