Pages

Wednesday, 11 September 2013

How to Load Java Properties File Dynamically From the Classpath

Why this properties file ? if we are using any application where there is a chance of constantly changing any credentials, something consider any java email application or any there you may need to change from,to or any properties right ? In this situation what you have to do is, opening .java file and doing the modifications and again re-compile and re-deploy.  Think what if you need to change 100′s of .java files :-) hmm 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  = java4s.properties



ClientLogic.javva

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package java4s;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
 
public class ClientLogic {
 
    public static void main(String... args)
    {
 
// First Way
 
        Properties prop = new Properties();
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("java4s.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("java4s.properties");
        try{
        prop.load(url.openStream());
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        System.out.println("------- By Using URL class -------");
        System.out.println(prop);
 
    }
}

No comments:

Post a Comment