Java Reference
In-Depth Information
You can read the entries from a JAR file using similar code to that you used to read entries from a ZIP file. To read
the entries from a manifest file of a JAR file, you need to get the object of the
Manifest
class using the
getManifest()
class of the
JarInputStream
as follows:
// Create a JAR input stream object
JarInputStream jis = new JarInputStream(new FileInputStream("jartest.jar"));
// Get the manifest file from the JAR file. Will return null if
// there is no manifest file in the JAR file.
Manifest manifest = jis.getManifest();
if (manifest != null) {
// Get the attributes from main section
Attributes mainAttributes = manifest.getMainAttributes();
String mainClass = mainAttributes.getValue("Main-Class");
// Get the attributes from individual section
Map<String, Attributes> entries = manifest.getEntries();
}
This section does not include code examples on reading entries from a JAR file. Please refer to the code in the
UnzipUtility
class, which has the code to read entries from a ZIP file. The code to read from a JAR file would be
similar, except you would be using JAR-related classes from the
java.util.jar
package instead of the ZIP-related
classes from the
java.util.zip
package.
Accessing Resources from a JAR File
How would you get access to the resources stored in a JAR file? For example, how would you get access to a file named
images/logo.bmp
in a JAR file, so that you can display the
bmp
file as an image in your java application?
You can construct a URL object by using the reference of a resource in a JAR file. The JAR file URL syntax is
of the form
jar:<url>!/{entry}
The following URL refers to an
images/logo.bmp
JAR entry in a
test.jar
file on
www.jdojo.com
using the HTTP
protocol:
The following URL refers to an
images/logo.bmp
JAR entry in a
test.jar
file on the local file system in the
c:\
jarfiles\
directory using the
file
protocol:
jar:file:/c:/jarfiles/test.jar!/images/logo.bmp
If you want to read the
images/logo.bmp
file from a JAR file in the classpath, you can get an input stream object
using a class object as follows:
// Assuming that the Test class is in the CLASSPATH
Class cls = Test.class;
InputStream in = cls.getResourceAsStream("/images/logo.bmp")