2016-08-18 87 views
0

我试图使用load(new FileReader())方法将属性加载到java中的Properties对象。所有的属性都被加载,除了以(#)注释的属性开始。如何使用Java API将这些注释的属性加载到Properties对象。只有手动的方式?将注释属性加载到java中的属性对象

在此先感谢。

回答

-1

我可以建议你扩展java.util.Properties类来覆盖这个特性,但它并不是为它设计的:很多东西都是硬编码的,不能被覆盖。所以你应该做很少修改的方法的整个复制粘贴。 例如,在一个时间,在内部使用的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")); 
}