【问题标题】:Load commented properties to Properties object in java将注释属性加载到 java 中的 Properties 对象
【发布时间】:2016-08-18 17:34:50
【问题描述】:

我正在尝试使用load(new FileReader()) 方法将属性加载到Java 中的Properties 对象。除了以 (#) 注释的属性开头的属性外,所有属性都已加载。如何使用 java API 将这些注释属性加载到 Properties 对象。只能手动吗?

提前致谢。

【问题讨论】:

    标签: java properties load comments


    【解决方案1】:

    我可以建议你扩展 java.util.Properties 类来覆盖这个特性,但它不是为它设计的:很多东西都是硬编码的,不能被覆盖。因此,您应该对方法进行完整的复制粘贴,而无需进行任何修改。 例如,当您加载属性文件时,internal 中使用的 LineReader 有时会这样做:

     if (isNewLine) {
                    isNewLine = false;
                    if (c == '#' || c == '!') {
                        isCommentLine = true;
                        continue;
                    }
     }
    

    # 是硬编码的。

    编辑

    另一种方法可以逐行读取属性文件,如果它是#,则删除第一个字符并将读取的行写入ByteArrayOutputStream中,如果需要修改。那么您可以使用来自ByteArrayOutputStream.toByteArray()ByteArrayInputStream 加载属性。

    这里有一个可能的单元测试实现:

    myProp.properties 为输入:

    dog=woof
    #cat=meow
    

    单元测试:

    @Test
    public void loadAllPropsIncludingCommented() throws Exception {
    
        // check properties commented not retrieved
        Properties properties = new Properties();
        properties.load(LoadCommentedProp.class.getResourceAsStream("/myProp.properties"));
        Assert.assertEquals("woof", properties.get("dog"));
        Assert.assertNull(properties.get("cat"));
    
        // action
        BufferedReader bufferedIs = new BufferedReader(new FileReader(LoadCommentedProp.class.getResource("/myProp.properties").getFile()));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String currentLine = null;
        while ((currentLine = bufferedIs.readLine()) != null) {
            currentLine = currentLine.replaceFirst("^(#)+", "");
            out.write((currentLine + "\n").getBytes());
        }
        bufferedIs.close();
        out.close();
    
        // assertion
        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        properties = new Properties();
        properties.load(in);
        Assert.assertEquals("woof", properties.get("dog"));
        Assert.assertEquals("meow", properties.get("cat"));
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 2013-09-30
      • 1970-01-01
      • 2019-03-30
      相关资源
      最近更新 更多