Search code examples
javapropertiesescapingkey-value

How do you escape colon (:) in Properties file?


I am using a properties file to store my application's configuration values. In one of the instances, I have to store a value as xxx:yyy:zzz. When I do that, the colon is escaped with a back slash\ resulting in the value showing as xxx\:yyy\:zzz in the properties file.

I am aware that the colon : is a standard delimiter of the Properties Java class. However I still need to save the value without the back slash \.

Any suggestions on how to handle this?


Solution

  • Put the properties into the Properties object and save it using a store(...) method. The method will perform any escaping required. The Java documentation says:

    "... For the key, all space characters are written with a preceding \ character. For the element, leading space characters, but not embedded or trailing space characters, are written with a preceding \ character. The key and element characters #, !, =, and : are written with a preceding backslash to ensure that they are properly loaded."

    You only need to manually escape characters if you are creating / writing the file by hand.


    Conversely, if you want the file to contain unescaped colon characters, you are out of luck. Such a file is malformed and probably won't load properly using the Properties.load(...) methods. If you go down this route, you'll need to implement your own custom load and/or store methods.