Properties files is a cool place to store your configuration details like database connection properties, error messages and other configurations to your program.
You can use the properties file in your application using following utility class. This class basically loads your properties file on first attempt to access any property on further attempts to access any Property It would return properties already loaded in memory and not attempt to read file again and again.
Static getProperty(String key)
method allows you-get property value by passing the key and static method Set<Object> getkeys()
returns a set of keys in T He file.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 6667686970 |
Package com. Bharat. Utils; import java. Io. FileNotFoundException; import java. Io. IOException; import java. Io. InputStream; import java. Util. Properties; import java. Util. Set; public class propertiesutil { private static Properties props; Static { props = new Properties(); try { propertiesutil util = new propertiesutil(); props = util. Getpropertiesfromclasspath("placeholder.properties"); } catch (filenotfoundexception e) { e. Printstacktrace(); } catch (ioexception e) { e. Printstacktrace(); } } //private constructor Private propertiesutil() { }Public static string getProperty(string key) { return props. GetProperty(key). Trim(); }Public static Set getkeys() { return props. KeySet(); } /*** Loads properties file from Classpath * * @param propfilename* @return* @throws IOException */ Private Properties getpropertiesfromclasspath(String propfilename) throws ioexception { Properties props = new Properties(); inputstream inputstream = This . GetClass(). getClassLoader(). getResourceAsStream(propfilename); if (inputstream = = null) { throw new filenotfoundexception("Property file" + propfilename + "' not found in the Classpath"); } props. Load(inputstream); return props; }} |
You could put your properties file anywhere in project ' s classpath.
References:
- Http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
- http://bharatonjava.wordpress.com/2012/09/12/using-properties-file-in-java-application/
- How to use the properties file in Java, read properties file, using properties file in Java
Using properties file in Java application