2016-05-25 23 views
2

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

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

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

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

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

编辑:任何指向正确的方向看它自己也会很好。

回答

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

+0

我用来访问获取资源的文件。这是正确的方法: 'File f = new File(this.getClass()。getClassLoader()。getResource(“cities.prop”)。getPath());' – Vale

+0

@Vale在我看来,这是可以的。看到这个:http://stackoverflow.com/a/1318386/3899583 – vojta