Home > Java > How to load properties file using ClassLoader

How to load properties file using ClassLoader

In Java, properties file is mostly used in common applications. And here’s one example how to load and read it using ClassLoader.


import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

public class PropertiesReader {

private Properties props = new Properties();

/**

* This function will load fileProps into a Properties

*

* @param fileProps

* @throws IOException

*/

public void loadProperties(String fileProps) throws IOException {

InputStream inpStream = null;

try {

inpStream = this.getClass().getClassLoader().getResourceAsStream(

fileProps);

this.props.load(inpStream);

} finally {

inpStream.close();

}

}

/**

* This function return value from the 'key'

*

* @param key

* @return properties value

*/

public String get(String key) {

return this.props.getProperty(key);

}

// tester

public static void main(String[] args) throws IOException {

PropertiesReader propsReader = new PropertiesReader();

propsReader.loadProperties("config.properties");// load properties

String content = propsReader.get("test.address");// load value

System.out.println(content);// print it

}

}

This my eclipse structure that i used in this project.

and my config.properties, only filled by one line,


test.address=https://namingexception.wordpress.com

The code is too long for you? don’t worry,tomorrow i will share about how to read properties only using 2 lines of codes. Really, in the 2 lines of codes :).

Advertisements
Categories: Java
  1. Denashkumar
    6 May 2015 at 17:47

    Thanks a lot for this explanation, past two days i got struggled with this issue now it’s working as expected after converting jar also/

    • RDeJourney
      13 May 2015 at 09:45

      hi @DenashKumar, i’m glad this is working for you 🙂

  1. 24 November 2010 at 01:00

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: