JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Checkout for Promo Codes

Program: How to load property file using class name in java?


Description:

This example shows how to load a property file using class name in java.


Code:
package com.java2novice.properties;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MyPropUsingClassName {

	private static Properties prop;
	
	static{
		InputStream is = null;
		try {
			prop = new Properties();
			is = MyPropUsingClassName.class.getResourceAsStream("/sample.properties");
			prop.load(is);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getPropertyValue(String key){
		return prop.getProperty(key);
	}
	
	public static void main(String a[]){
		
		System.out.println("db.host: "+getPropertyValue("db.host"));
		System.out.println("db.user: "+getPropertyValue("db.user"));
		System.out.println("db.password: "+getPropertyValue("db.password"));
	}
}

Output:
db.host: appdomain.java2novice.com
db.user: java2novice
db.password: mypassword
<< Previous Program 

List of Properties class sample programs:

  1. How to load Properties file from a file system?
  2. How to load Properties file from the classpath?
  3. How to load Properties file from a static block or static method?
  4. How to assign default values for unavailable keys in properties file?
  5. How to get all keys from properties file?
  6. How to create and store property file dynamically?
  7. How to store property file as xml file?
  8. How to load property file using class name in java?
Knowledge Centre
What is race condition?
A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and subtle program bugs. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked.
Famous Quotations
Do not confuse motion and progress. A rocking horse keeps moving but does not make any progress.
-- Alfred A. Montapert

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2020 by Nataraja Gootooru. All Rights Reserved.