By now, you may have noticed that every demo and solution folder contains its own copy of
KeyboardReader. Not only is it inefficient, but it means that we would have to locate and update each copy if we wanted to change
A better solution would be to have one master copy somewhere that all of our exercises could access.
Java has a CLASSPATH concept that enables you to specify multiple locations for
.class files, at both compile-time
By default, Java uses
rt.jar in the current Java installation's
jre/lib directory, and assumes that the classpath is the current directory (the working directory in an IDE).
If you create a classpath, the default one disappears, so any classpath that you create must include the current directory using a period (.) character.
To use an external library, you would need to create a classpath in one of two ways:
-cpis a shorthand version of that).
Here is an example of a pair of commands to compile and run using an external library stored in a jar file. Note that we need the jar file at both compile-time and runtime. The
-cp option in both commands replaces the system classpath with one specifically for that command.
javac -cp c:\Java102\ClassFiles\utilities.jar;. *.java java -cp c:\Java102\ClassFiles\utilities.jar;. Payroll
Many Integrated Development Environments (IDEs) have a means to specify project properties; usually an item like "Build Path" will have options to specify external jar files (as well as choose from various libraries supplied with the environment).
jarFile (a Library)
If you wish to create your own library of useful classes, you can bundle one or more classes and/or directories of classes in a jar file. Yyou can also add other resources such as image files.
A jar file contains files in a zipped directory structure. The root level of the file structure should match the root of the package structure; for example, to put
KeyboardReader in a
jar file, we would want to start at the directory where
util is visible, and
The following command will create a
jar file called
utilities.jar for all files in the
util package (just
KeyboardReader, in this case).
jar -cvf utilities.jar util\*.class