Using getResourceAsStream() in STATIC method- Reading property Files

In our previous tutorial I have discussed how to read the property files using FileInputStream and create and write files using FileOutputStream in Java but that works when we have stored our file in our project root folder.

But there are cases when we have to store the files in our classpath folder. So in such cases we are not required to provide the path we just use getClass().getClassLoader().getResourceAsStream(“Resource-Name”) but only when we are not accessing it from static method.

File -> config.properties
#Sun Aug 24 13:34:24 IST 2014
password=Codingeek
database=localhost
username=Codingeek

So generally we do like this when we read from a Non Static Method but be sure that your file is in the src folder of your project.

public class ReadPropertyFile {
	public static void main(String[] args) {

		//Call to non static method
		new ReadPropertyFile().readFileNonStatic();
	}

	private  void readFileNonStatic() {
		Properties prop = new Properties();

                //try with resource.. Works only from Java 7
		try (InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties")) {

			// load a properties file
			prop.load(input);

			// get the property value and print it out
			System.out.println("Database - " + prop.getProperty("database"));
			System.out.println("Username - " + prop.getProperty("username"));
			System.out.println("Password - " + prop.getProperty("password"));

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

Output:-
Database – localhost
Username – Codingeek
Password – Codingeek

In Static Method this way of getting resource does not work as it says

Cannot make a static reference to the non-static method getClass() from the type Object

So here is the way of using it in a static method. Instead of using getClass() -> User ClassName.class.

public class ReadPropertyFile {
	public static void main(String[] args) {
		Properties prop = new Properties();

		//try with resource.. Works only from Java 7
		try(InputStream input = ReadPropertyFile.class.getClassLoader().getResourceAsStream("config.properties")) {

			// load a properties file
			prop.load(input);

			// get the property value and print it out
			System.out.println("Database - " + prop.getProperty("database"));
			System.out.println("Username - " + prop.getProperty("username"));
			System.out.println("Password - " + prop.getProperty("password"));

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

Output:-
Database – localhost
Username – Codingeek
Password – Codingeek

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x