Read a file from resource file in Java

Hello coders in this tutorial, we will discuss a method for reading a file from a resource folder in Java.

We can read the file using the ClassLoader object before we proceed firstly we will discuss ClassLoader.

What is ClassLoader?

ClassLoader is a class in Java that is used to load class files, it is used to load classes at runtime.

 

If you ever make a Java project then you already know the location of the resource folder, it’s location src/java/resources

Code for reading from the resource folder:-

ClassLoader classLoader = this.getClass().getClassLoader();
File configFile=new File(classLoader.getResource(fileName).getFile());

Now the whole code for the reading a file from the resource folder:-

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadPropertiesFileJavaMain {
 public static void main(String args[]) throws IOException
 {
  ReadPropertiesFileJavaMain rp=new ReadPropertiesFileJavaMain();
  System.out.println("Reading a file from theresources folder");
  System.out.println("****************************");
 
  rp.readFile("config.txt");
  
  System.out.println("****************************");
 }
 
 public  void readFile(String fileName) throws IOException
 {
  FileInputStream inputStream=null;
  
  try {
   ClassLoader classLoader = this.getClass().getClassLoader();
   File configFile=new File(classLoader.getResource(fileName).getFile());
   inputStream = new FileInputStream(configFile);
   BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
   String line;
   while ((line = reader.readLine()) != null) {
   System.out.println(line);
   }
 
   reader.close();
 
 
  } catch (FileNotFoundException e) {
 
   e.printStackTrace();
  }catch (IOException e) {
 
   e.printStackTrace();
  }
  finally {
   inputStream.close();
  }
 
  
 }
 
}

Output:-

Reading a file from the resources folder
****************************
host = localhost
username = tony
password = zxcvbnm123
****************************

 

Leave a Reply

Your email address will not be published. Required fields are marked *