Java - JAR File Resources Accessing

Introduction

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.book2s.com using the HTTP protocol:

jar:http://www.book2s.com/test.jar!/images/logo.bmp

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

To read the images/logo.bmp file from a JAR file in the classpath, 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")

You can get a URL object for an entry in your JAR file, which is in your classpath as follows:

URL url = cls.getResource("/images/logo.bmp");

Related Topic