Raghottam
Raghottam

Reputation: 3

How to ignore backslashes appearing in the properties file for characters like : and =

private static void createPropertiesFile() {
    Properties prop = new Properties();
    OutputStream output = null;

    try {

        output = new FileOutputStream(
                "c://properties//xyz.properties");

        // set the properties value
        prop.setProperty("URL", hostName);

        prop.store(output, null);

    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

Sample data in properties file looks as below.

#Tue Oct 06 15:26:55 IST 2015
URL=jdbc\:sqlserver\://abc.xyz.net

My understand is that anything before first "=" is treated as key and anything after first "=" as treated as value. In the process, when characters like : and = are encountered,they are escaped with backslash, '\'.

Can anyone please help me on how to remove or restrict '\' from appearing in first place in properties file when encountered with : and =

Upvotes: 0

Views: 2171

Answers (1)

Dave G
Dave G

Reputation: 9767

This is by design. Properties files will treat = and : as key/value delimiters.

To make it explicit as to which part is the key and which is the value the '=' and ':' characters, if included in either part, must be escaped.

Consider the following:

Key: somepassword
Value: Xj993a==

Your properties file will look like:

somepassword=Xj993a==

Unfortunately, where is the key and where is the value? The key could be:

  • somepassword with value Xj993a==
  • somepassword=Xj993a with value =
  • somepassword=Xj993a== with empty value

The parsing of this would be ambiguous at best. Now if we escape the '=' characters:

somepassword=Xj993a\=\=

This is now EXPLICITLY clear as to which is the key and which is the value.

This could also easily have been written as:

somepassword:Xj993a\=\=

Please read the documentation of java.util.Properties.load(java.io.Reader) for more information on the escapes allowed and parsing semantics of properties files.

Upvotes: 1

Related Questions