Table of Contents
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.
1 2 3 4 5 6 |
// 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
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(); } } } |
1 2 3 4 5 6 7 8 |
Reading file from resources folder ----------------------------- host = localhost username = java2blog password = java123 ----------------------------- |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.