0
我試圖使用load(new FileReader())
方法將屬性加載到java中的Properties對象。所有的屬性都被加載,除了以(#)註釋的屬性開始。如何使用Java API將這些註釋的屬性加載到Properties對象。只有手動的方式?將註釋屬性加載到java中的屬性對象
在此先感謝。
我試圖使用load(new FileReader())
方法將屬性加載到java中的Properties對象。所有的屬性都被加載,除了以(#)註釋的屬性開始。如何使用Java API將這些註釋的屬性加載到Properties對象。只有手動的方式?將註釋屬性加載到java中的屬性對象
在此先感謝。
我可以建議你擴展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"));
}