Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are colons escaped with a backslash when you generate a properties file using the Java API? [duplicate]

Sample code:

public final class Test
{
    public static void main(final String... args)
        throws IOException
    {
        final Properties properties = new Properties();

        properties.setProperty("foo", "bar:baz");

        // Yeah, this supposes a Unix-like system
        final Path path = Paths.get("/tmp/x.properties");

        try (
            // Requires Java 8!
            final Writer writer = Files.newBufferedWriter(path);
        ) {
            properties.store(writer, null);
        }
    }
}

Now, when I:

$ cat /tmp/x.properties 
# The date here
foo=bar\:baz

the colon is escaped with a backslash. In fact, all colons are.

The strange thing is that if I generate a properties file by hand and do not "escape" the colon, the properties are read just as well.

So, why does the writing process of Properties (this is the case whether you use a Writer or OutputStream by the way) escape colons this way?

like image 462
fge Avatar asked Oct 18 '22 05:10

fge


1 Answers

The load method of the Properties class mention the following:

The key contains all of the characters in the line starting with the first non-white space character and up to, but not including, the first unescaped '=', ':', or white space character other than a line terminator. All of these key termination characters may be included in the key by escaping them with a preceding backslash character;

...

As an example, each of the following three lines specifies the key "Truth" and the associated element value "Beauty":

Truth = Beauty

Truth:Beauty

Truth :Beauty

So the colon can be used to determine the end of the key in a property file.

like image 159
M A Avatar answered Oct 21 '22 05:10

M A