Read a file from resources folder in java

In this post, we will see how to read a file from resources folder in java. If you create a maven project(simple java or dynamic web project) , you will see folder src/java/resources. You can read from resources folder using these simple code.

 
                        // Getting ClassLoader obj
   ClassLoader classLoader = this.getClass().getClassLoader();
   // Getting resource(File) from class loader
   File configFile=new File(classLoader.getResource(fileName).getFile());

Project structure:

Java Program:

package org.arpit.java2blog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
/*
 * @author Arpit Mandliya
 */
public class ReadPropertiesFileJavaMain {

 public static void main(String args[]) throws IOException
 {
  ReadPropertiesFileJavaMain rp=new ReadPropertiesFileJavaMain();
  System.out.println("Reading file from resources folder");
  System.out.println("-----------------------------");

  rp.readFile("config.txt");
  
  System.out.println("-----------------------------");
 }

 public  void readFile(String fileName) throws IOException
 {
  FileInputStream inputStream=null;
  
  try {
   // Getting ClassLoader obj
   ClassLoader classLoader = this.getClass().getClassLoader();
   // Getting resource(File) from class loader
   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();
  }

  
 }

}

When you run above program, you will get following output.
Reading file from resources folder
-----------------------------
host = localhost
username = java2blog
password = java123
-----------------------------

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012