Java Reference
In-Depth Information
to distribute Java code, and the exam tests your understanding of JAR fi les and how they
relate to CLASSPATH .
The JDK comes with the tool jar.exe for creating and extracting JAR fi les. The
following command adds the bytecode fi les of the c:\myproject\build directory to a new
JAR fi le named myproject.jar :
C:\myproject\build>jar -cvf myproject.jar .
added manifest
adding: com/(in = 0) (out= 0)(stored 0%)
adding: com/sybex/(in = 0) (out= 0)(stored 0%)
adding: com/sybex/demos/(in = 0) (out= 0)(stored 0%)
adding: com/sybex/demos/TestColors.class(in = 1209) (out= 671)(deflated 44%)
adding: com/sybex/events/(in = 0) (out= 0)(stored 0%)
adding: com/sybex/events/ColorChanger.class(in = 883) (out= 545)(deflated 38%)
adding: com/sybex/payroll/(in = 0) (out= 0)(stored 0%)
adding: com/sybex/payroll/Employee.class(in = 402) (out= 292)(deflated 27%)
The -c fl ag is for creating a new JAR fi le. The -v fl ag tells the jar command to be
verbose while it is processing fi les. The -f fl ag is for denoting the fi lename of the new
JAR fi le, which in this example is myproject.jar . After the fi lename, you specify the
fi les or directories to include in the JAR. In our example, because all of our bytecode was
conveniently located in the \build directory, we simply added the entire contents of
c:\myproject\build , using the dot to represent the current directory.
JAR Files and Package Names
If a class is in a package, then the JAR fi le must contain the appropriate directory structure
when the .class fi le is included in the JAR. Notice in the verbose output of the jar
command shown earlier, the necessary \com directory and subdirectories matching our
package names are added to the JAR.
You can add a JAR fi le to your CLASSPATH . In fact, it is common to have lots of JAR
fi les in your CLASSPATH . The following example demonstrates adding myproject.jar to
the CLASSPATH of a Windows machine, then running the TestColors program (which is in
myproject.jar ):
C:\>set CLASSPATH=c:\myproject\build\myproject.jar;
C:\>java com.sybex.demos.TestColors
Color is java.awt.Color[r=0,g=255,b=0]
Now the color is java.awt.Color[r=0,g=0,b=255]
Search WWH ::




Custom Search