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

前端之家收集整理的这篇文章主要介绍了使用Java API生成属性文件时,为什么使用反斜杠转义冒号?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参见英文答案 > Saving to properties file escapes :                                    2个
示例代码

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

冒号用反斜杠逃脱.事实上,所有的冒号都是.

奇怪的是,如果我手动生成属性文件并且不“冒走”冒号,那么也会读取属性.

那么,为什么属性的写入过程(无论你是使用Writer还是OutputStream都是这种情况)以这种方式逃避冒号?

最佳答案
Properties类的加载方法提到以下内容

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

因此冒号可用于确定属性文件中键的结尾.

猜你在找的Java相关文章