Generally properties file is a simple key value file, which will be useful in software coding to extract the common code from the class files, like database connection attributes, queries, constants, etc. This will make the code easy for maintenance.
Below is a sample code piece on how to read the values from properties file using resourcebundle.
create a file named prop.properties, with the below contents
Filename >>prop.properties<< (below are the contents in the file)
propkey1=propvalue1
propkey2=propvalue2
if using eclipse create a java project and use the below code in a class file.
File/java class name >>PropertyResourcebundEx<<
import java.util.ResourceBundle;
public class PropertyResourcebundEx {
public static void main(String args[])
{
//Below is the declaration to get the instance of the property file.
//the prop.properties file should be within the class path, as the resourcebundle can read the properties file.
//prop is the properties file name
// there is no necessity to provide the extension of the properties file as this file is within the class path.
ResourceBundle rsbundle = ResourceBundle.getBundle("prop");
//below is the code which will get the information of the prop file
//getSring() method of the resourcebundle will get the value of the key propkey1 from the property file
String PROP_VAL1 = rsbundle .getString("propkey1");
String PROP_VAL2 = rsbundle .getString("propkey2");
System.out.println("Propval1 & propval2 = " + PROP_VAL1+ " && "+ PROP_VAL2);
}
}
Output:
>> Propvalue1 & propval2 = propvalue1 && propvalue2
Note: if the prop.properties file is not within the class path, then we get the below exception:
Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name prop, locale en_US
at java.util.ResourceBundle.throwMissingResourceException(Unknown Source)
at java.util.ResourceBundle.getBundleImpl(Unknown Source)
at java.util.ResourceBundle.getBundle(Unknown Source)
at com.test.mail.PropertyResourcebundEx.main(PropertyResourcebundEx.java:12)
No comments:
Post a Comment