Load a resource from the classpath

suggest change

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");

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


The Classpath:
* Load a resource from the classpath

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
84 The Classpath
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap