2012-04-16 69 views
15

是否有可能在Java中堆栈加载的属性?例如,我可以这样做:加载多个属性文件

Properties properties = new Properties(); 

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

和访问属性?

+1

是的,如果属性具有不同的名称。不,如果这些属性具有相同的名称。如果属性名称冲突,则必须自己提供堆叠。 – Jesse 2012-04-16 20:37:14

回答

28

你可以这样做:

Properties properties = new Properties(); 

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

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

properties.putAll(properties2); 
+5

如果file2.properties包含与file1.properties中定义的属性具有相同名称的属性,则仅存在file2.properties中这些属性的值。 – Jesse 2012-04-16 20:35:52

+0

对。您无法同时保留这两个属性,因为键必须是唯一的。 – 2012-04-16 20:38:06

+0

推荐的方法是在构造函数中传递默认属性文件。该属性扩展地图只是一个实现细节。 – Puce 2012-04-16 20:39:00

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

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

+0

推荐的方法是在构造函数中传递默认属性文件。该属性扩展地图只是一个实现细节。 – Puce 2012-04-16 20:42:54

+1

此行为未由“属性”合约声明(换句话说,未记录使用未记录功能的所有可能后果)。 – 2012-04-16 20:43:26

+0

这是事实,应该加以考虑。我只是对实际结果感兴趣,而不是记录在案的行为。 – tskuzzy 2012-04-16 20:47:55

3

其实,是的。你可以这样做。如果任何属性重叠,则新的加载属性将替换较旧的属性。

2

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

例如为:

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

起初我很喜欢这个,但现在我有所保留。抛开BufferedInputStream的使用,这比OP的代码更好吗?在这两种情况下,您都要将第二个文件直接加载到包含第一个文件属性的Properties对象中。但在这个例子中,你正在创建一个新的属性对象。有什么好处? – datguy 2014-07-17 15:23:22

+0

如果您使用此方法,并且由于某种原因正在迭代属性,您必须**使用'propertyNames()'或'stringPropertyNames()'获取列表进行迭代。如果使用'entrySet()'或'keySet()'等底层'Map'方法,那么构造函数中指定的属性将不会被包含。 – 2016-08-10 15:46:46

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。

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