How to Load Java
Properties File Dynamically From the Classpath?
What is the purpose
of properties file? if we are using any application or project where
there is a chance of constantly changing any credentials, for example any java email application or any there you may need to
change from address, to address or any properties right ? For
this opening .java file and doing the modifications and again re-compile and
re-deploy if you need to change 100′s of .java files its very tedius
job right so this .properties file.
We will place this
.properties file in general at classpath location, will see how to load that
properties file into .java programs and how to use it. In this application my
properties file name = orderworkbench.properties
Clientprograme.java
package chandra;
import
java.io.IOException;
import
java.io.InputStream;
import
java.net.URL;
import
java.util.Properties;
public class Clientprograme {
public static void main(String args[])
{
// First Way
Properties prop =
new Properties();
InputStream
inputStream =
Thread.currentThread().getContextClassLoader().getResourceAsStream("orderworkbench.properties");
try{
prop.load(inputStream);
}catch(IOException
e)
{
e.printStackTrace();
}
System.out.println("-------
By Using Thread class -------");
//Print required
values
System.out.println(prop.get("user"));
//Print all the
properties
System.out.println(prop);
// Second Way
URL url =
ClassLoader.getSystemResource("orderworkbench.properties");
try{
prop.load(url.openStream());
}catch(Exception
e)
{
e.printStackTrace();
}
System.out.println("-------
By Using URL class -------");
System.out.println(prop);
}
}
Post a Comment
Post a Comment