Pages

Thursday, July 31, 2008

Java Properties File - Some less known facts

I came across a problem using java properties file, and I think, its a good piece to go here. I am sure, majority of the developer who are new to java(even some oldies) may encounter this issue.

The properties file contents:

a0=impl1
a1:sol1=impl2

The java program is below:

public static void main(String[] args) {
        Properties properties = new Properties();
        try {//Assume, no problemo finding properties file
            properties.load(Tester.class.getClassLoader().getResourceAsStream("test.properties"));
            System.out.println(properties.getProperty("a0"));
            System.out.println(properties.getProperty("a1:sol1"));            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

Surprisingly the output of the following program is:

a0=impl1
null

When you do properties.list(System.out), I was little surprised to see:

a0=impl1
a1=sol1=impl2

The ':' has been converted to '='.

Finally, with the help of wiki I found that, the name value pairs in the java properties file can be of formats:

a. name=value (This all us know definitely know)
b. name:value c. name value

And, the solution is to escape the special character using backslash. That is in the properties file,

a0=impl1
a1\:sol1=impl2

Hope this helps someone who is surprised to see 'un-expected' output.

1 comment:

  1. thanks so much!!

    I got the same trouble

    :P

    ReplyDelete