Loading Resources from Classpath in Java with Example
Resources are the collections of files or images or stuff of other formats. Java programs help us to load these files or images of the resources and perform a read and write operation on them. For example, we can load a file from any resource directory and will be then able to read the content of that file. Basically, we are mainly focusing on the topic of loading and not on how to read the files, but we will be using some ideas of how to read files to demonstrate our examples.
There are mainly two ways to load resources and perform operations on them. We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL’s and input streams respectively. These methods are present in the java.lang.Class package.
So here we are taking getting absolute classpath using classLoader() method. Also, we are using the getClass() method here to get the class whose path is to be loaded. Basically, it will be the class of the .class file of our code. So we should make sure that the resources are located in the path of the class.
So to load the file from the name itself using classpath is done by combining all the above-discussed method. After getting the file we have to read its content, so we will be performing a read operation on them.
We will be using obj.getClass().getClassLoader().getResourceAsStream() and obj.getClass().getClassLoader().getResource() methods to get the stream and URL of the file respectively and then perform the read operations on them.
So two main points to consider here are:
- Here we are declaring the object of the public class of our file since the getClass() method is non-static. So we cannot call this method without an object.
- In the below code, we are considering file named GFG_text.txt which acts as a resource, and we are taking care that this resource is in same path as that of our .class file.
Code 1: Using getResourceAsStream() method.
Code 2: Using getResource() method.