从单个文件为多个类实例加载多个属性集

时间:2016-05-25 08:56:00

标签: java properties instance

我有一个类,如果其中一个属性发生变化,我需要一个不同的实例。这些更改在运行时从属性文件中读取。 我想有一个文件详细说明所有单个实例的属性:

------------
name=Milan
surface=....
------------
name=Naples
surface=....

如何在不同的Property类中加载每组属性(可能创建Properties[])?是否有Java内置方法可以这样做? 我应该手动解析它,如何在集合中找到除法字符串时如何创建一个InputStream?

ArrayList<Properties> properties = new ArrayList<>();
if( whateverItIs.nextLine() == "----" ){
        InputStream limitedInputStream = next-5-lines ;
        properties.add(new Properties().load(limitedInputStream));
}

像上面这样的东西。顺便说一句,任何直接从文件创建类的构造函数方法?

编辑:任何指向正确方向的人都会很好看。

1 个答案:

答案 0 :(得分:2)

首先,将整个文件作为单个字符串读取。然后使用splitStringReader

String propertiesFile = FileUtils.readFileToString(file, "utf-8");
String[] propertyDivs = propertiesFile.split("----");
ArrayList<Properties> properties = new ArrayList<Properties>();

for (String propertyDiv : propertyDivs) {
     properties.add(new Properties().load(new StringReader(propertyDiv)));
}

上面的示例使用apache commons-io库将文件传递给String一行,因为Java没有这样的内置方法。但是,使用标准Java库可以轻松实现读取文件,请参阅Whole text file to a String in Java