Open In App

Loading Resources from Classpath in Java with Example

Last Updated : 05 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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:

  1. 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.
  2. 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.

Java




// Java program to load resources from Classpath
// using getResourceAsStream() method.
  
import java.io.*;
import java.nio.file.Files;
  
//save file as the name of GFG2
public class GFG2 {
    
    //main class
    public static void main(String[] args) throws Exception {
        
        // creating object of the class
        // important since the getClass() method is 
        // not static.
        GFG2 obj = new GFG2();
        
        // name of the resource
        // the resource is stored in our base path of the 
        // .class file.
        String fileName = "GFG_text.txt";
          
        System.out.println("Getting the data of file " + fileName);
        
        // declaring the input stream
        // and initializing the stream.
        InputStream instr = obj.getClass().getClassLoader().getResourceAsStream(fileName);
  
        // reading the files with buffered reader 
        InputStreamReader strrd = new InputStreamReader(instr);
         
        BufferedReader rr = new BufferedReader(strrd);
  
        String line;
        
        // outputting each line of the file.
        while ((line = rr.readLine()) != null
                System.out.println(line);
            
}



output of the above program.

Code 2: Using getResource() method.

Java




// Java program to load resources from Classpath
// using getResource() method.
  
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
  
//save file as the name of GFG2
public class GFG2 {
    
    //main class
    public static void main(String[] args) throws Exception {
        
        // creating object of the class
        // important since the getClass() method is 
        // not static.
        GFG2 obj = new GFG2();
        
        // name of the resource
        // the resource is stored in our base path of the 
        // .class file.
        String fileName = "GFG_text.txt";
          
        System.out.println("Getting the data of file " + fileName);
        
        // getting the URL of the resource
        // and creating a file object to the given URL
        URL url = obj.getClass().getClassLoader().getResource(fileName);
        
        File file = new File(url.toURI());
        
        // reading the file data 
        // by creating a list of strings 
        // of each line
        List<String> line;
        
        // method of files class to read all the lines of the 
        // file specified.
        line = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
        
        // reading the list of the line in the file.
        for(String s: line)
            System.out.println(s);
    }
}



output for the second code.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads