2012-04-16 71 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(); 
    } 
}