Week 11: classpath and packaging in Java
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 other systems), just like
Setting the classpath
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
flag each time you run
javac, which looks like this on Windows:
java -cp ".;other\directory;somejarfile.jar" MyClass
. 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
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 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
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:
ant to create the jar file, but we could use the
to build it instead. Running from within the
build directory, use the
jar cfe Hello.jar HelloGUI *.class
The first argument is always an acronym for the operation to perform. Here,
cfe stands for
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.
This jar file tutorial covers many of the details (what we used plus a
lot more) of working with jar files and the