【问题标题】:Loading multiple properties sets from single file for multiple class instances从单个文件为多个类实例加载多个属性集
【发布时间】:2016-05-25 08:56:00
【问题描述】:

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

------------
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));
}

类似上面的东西。而且,顺便问一下,任何直接从文件创建类的构造方法?

编辑:任何指向正确的方向来为自己寻找它也可以。

【问题讨论】:

    标签: java properties instance


    【解决方案1】:

    首先,将整个文件作为单个字符串读取。然后使用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

    【讨论】:

    • 我用来访问我的文件以获取资源。这是正确的方法吗:File f = new File(this.getClass().getClassLoader().getResource("cities.prop").getPath());
    • @Vale 在我看来没问题。看到这个:stackoverflow.com/a/1318386/3899583
    猜你喜欢
    • 2012-04-28
    • 2016-06-18
    • 2019-03-30
    • 2016-03-07
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多