加载多个属性文件

时间:2012-04-16 20:29:25

标签: java properties-file

是否可以在Java中堆叠加载的属性?例如,我可以这样做:

Properties properties = new Properties();

properties.load(new FileInputStream("file1.properties"));
properties.load(new FileInputStream("file2.properties"));

并从两者访问属性?

6 个答案:

答案 0 :(得分:30)

你可以这样做:

Properties properties = new Properties();

properties.load(new FileInputStream("file1.properties"));

Properties properties2 = new Properties();
properties2.load(new FileInputStream("file2.properties"));

properties.putAll(properties2);

注意:所有维护的密钥都是唯一的。因此,将覆盖使用相同键加载的后续属性。只是为了你的参考:)

答案 1 :(得分:8)

是属性堆栈。 Properties扩展Hashtableload()只需在每个键值对上调用put()

Source的相关代码:

String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf); 
String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf); 
put(key, value); 

换句话说,从文件加载不会清除当前条目。但请注意,如果两个文件包含具有相同键的条目,则第一个将被覆盖。

答案 2 :(得分:3)

实际上,是的。你可以这样做。如果任何属性重叠,则较新的加载属性将取代较旧的属性。

答案 3 :(得分:2)

是的,您需要在构造函数中传递默认属性文件。像这样,你可以把它们链起来。

E.g:

Properties properties1 = new Properties();
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("file1.properties"))){
    properties1.load(bis);
}

Properties properties2 = new Properties(properties1);
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("file2.properties"))){
    properties2.load(bis);
}

答案 4 :(得分:1)

这也应该有用。如果在file1.properties和file2.properties中定义了相同的属性,则file2.properties中的属性将生效。

    Properties properties = new Properties();
    properties.load(new FileInputStream("file1.properties"));
    properties.load(new FileInputStream("file2.properties"));

现在,属性映射将包含两个文件的属性。如果在file1和file2中出现相同的密钥,则file1中的密钥值将在file2中的值中更新,因为我正在调用file1然后调用file2。

答案 5 :(得分:1)

您可以使用不确定数量的文件进行更具动态性的操作。

此方法的参数应该是包含属性文件路径的列表。我将方法设置为静态,将其放在具有其他消息处理相关函数的类上,并在需要时简单地调用它:

public static Properties loadPropertiesFiles(LinkedList<String> files) {
    try {
        Properties properties = new Properties();

                for(String f:files) {
                    Resource resource = new ClassPathResource( f );
                    Properties tempProp = PropertiesLoaderUtils.loadProperties(resource);
                    properties.putAll(tempProp);
                }
                return properties;
    }
    catch(IOException ioe) {
                return new Properties();
    }
}
相关问题