使用 Java API 生成属性文件时,为什么冒号会用反斜杠转义?

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

示例代码:

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);
        }
    }
}

现在,当我:

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

冒号用反斜杠转义。事实上,所有的冒号都是。

奇怪的是,如果我手动生成一个属性文件并且 "escape"冒号,属性也会被读取。

那么,为什么Properties的写法(顺便说一下用WriterOutputStream都是这样)的冒号转义?

因为属性文件语法允许使用冒号作为键和值之间的分隔符而不是等号(你可以只使用 space),所以如果你更改分隔符以防止出现问题,可以将它们转义好主意。

例如:

# Add spaces to the key
key\ 2 = value for "key 2"
# colon :
key3: This is key 3
#space
key4 This is key 4

您可以查看 wikipedia entry

中的其他选项

load 方法 Properties class 提及以下内容:

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

因此冒号可用于确定 属性 文件中密钥的结尾。