Java Language Load a resource from the classpath


Example

It can be useful to load a resource (image, text file, properties, KeyStore, ...) that is packaged inside a JAR. For this purpose, we can use the Class and ClassLoaders.

Suppose we have the following project structure :

program.jar
|
\-com
  \-project
    |
    |-file.txt
    \-Test.class  

And we want to access the contents of file.txt from the Test class. We can do so by asking the classloader :

InputStream is = Test.class.getClassLoader().getResourceAsStream("com/project/file.txt");

By using the classloader, we need to specify the fully qualified path of our resource (each package).

Or alternatively, we can ask the Test class object directly

InputStream is = Test.class.getResourceAsStream("file.txt");

Using the class object, the path is relative to the class itself. Our Test.class being in the com.project package, the same as file.txt, we do not need to specify any path at all.

We can, however, use absolute paths from the class object, like so :

 is = Test.class.getResourceAsStream("/com/project/file.txt");