|
How to See What's in a Jar:
-
Run the jar command and give it the "table of contents", "verbose", and "file" options. It will print the names of the files in the jar:
% jar -tvf game.jar
How to Make a Jar Available to the JVM by adding it to the Classpath:
How to Create a Jar:
- Use the "jar" command, shown below with the options 'c'reate, 'v'erbose, and 'f'ile. Note that the syntax is similar to the Unix "tar" command. The command below creates (or overwrites) a file called someName.jar whose contents include a copy of all the .class files found in the current directory. The original .class files remain unchanged.
% jar -cvf game.jar *.class
- The Java compiler and JVM can find the jar (when resolving/finding class names) if the jar is in the same directory where javac/java is run,
or if the jar is in a directory in the invoker's CLASSPATH variable.
- If you want the Jar to be run as an application (e.g. to put all the class files for a game you've written in to a jar and run the game),
the JVM needs to know which class' main method to use as a starting point.
To "tell it":
- Create a "manifest"
file that contains the name of the class which has the special main method.
E.g. a file called "manifest.txt" with contents like this:
Main-Class: NameOfClassWhoseMainMethodShouldBeRun
- Create the Jar:
jar -cvmf manifest.txt myApplication.jar *.class
- Run the Jar as an application from the command line:
% java -jar myApplication.jar
- Depending on the operating system, you may be able to simply click or double-click on a jar's icon to run the application contained in it.
- Can a directory be put in to a jar?
Only if the directory is a package. One or more packages can be put in to a jar. (See next bullet)
- To add a package to a jar:
At the top of each class file:
package package_name;
Example 1: package chessgame;
Example 2: package net.coolgames.chessgame
To designate a main() method for the jar, create a manifest file in which a line should appear like so:
Main-Class: package_name.NameOfClassWhoseMainMethodShouldBeRun
Example 1: Main-Class: chesswiz.Main
Example 2: Main-Class: net.coolgames.chesswiz.Main
Create the jar:
jar -cvmf manifest.txt jar_name.jar package_directory_pathname
Example 1: jar -cvmf manifest.txt Chess.jar chessgame
Example 2: jar -cvmf manifest.txt Chess.jar net/coolgames/chessgame
How to Extract a File from a Jar:
% jar -xvf game.jar filename
|