是否有可能在Java中堆棧加載的屬性?例如,我可以這樣做:加載多個屬性文件
Properties properties = new Properties();
properties.load(new FileInputStream("file1.properties"));
properties.load(new FileInputStream("file2.properties"));
和訪問屬性?
是否有可能在Java中堆棧加載的屬性?例如,我可以這樣做:加載多個屬性文件
Properties properties = new Properties();
properties.load(new FileInputStream("file1.properties"));
properties.load(new FileInputStream("file2.properties"));
和訪問屬性?
你可以這樣做:
Properties properties = new Properties();
properties.load(new FileInputStream("file1.properties"));
Properties properties2 = new Properties();
properties2.load(new FileInputStream("file2.properties"));
properties.putAll(properties2);
是屬性疊加。 Properties
擴展爲Hashtable
和load()
只需在每個鍵值對上調用put()
。從Source
相關代碼:
String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
put(key, value);
換句話說,從文件加載不清除當前的條目。但是,請注意,如果這兩個文件包含具有相同密鑰的條目,則第一個文件將被覆蓋。
其實,是的。你可以這樣做。如果任何屬性重疊,則新的加載屬性將替換較舊的屬性。
是的,你需要在構造函數中傳遞默認的屬性文件。像這樣,你可以將它們鏈接起來。
例如爲:
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);
}
起初我很喜歡這個,但現在我有所保留。拋開BufferedInputStream的使用,這比OP的代碼更好嗎?在這兩種情況下,您都要將第二個文件直接加載到包含第一個文件屬性的Properties對象中。但在這個例子中,你正在創建一個新的屬性對象。有什麼好處? – datguy 2014-07-17 15:23:22
如果您使用此方法,並且由於某種原因正在迭代屬性,您必須**使用'propertyNames()'或'stringPropertyNames()'獲取列表進行迭代。如果使用'entrySet()'或'keySet()'等底層'Map'方法,那麼構造函數中指定的屬性將不會被包含。 – 2016-08-10 15:46:46
這也應該工作。如果在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。
您可以使用更多的動態操作來處理不確定數量的文件。
此方法的參數應該是一個帶有屬性文件路徑的列表。我將該方法設置爲靜態方法,將其放在具有其他消息處理相關函數的類上,只需在需要時調用它即可:
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();
}
}
是的,如果屬性具有不同的名稱。不,如果這些屬性具有相同的名稱。如果屬性名稱衝突,則必須自己提供堆疊。 – Jesse 2012-04-16 20:37:14