加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 01:06:12 所属栏目:Java 来源:网络整理
导读:参见英文答案 Saving to properties file escapes :????????????????????????????????????2个 示例代码: public final class Test{ public static void main(final String... args) throws IOException { final Properties properties = new Properties();

参见英文答案 > 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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读