두 개의 java.util.Properties 객체를 병합하는 방법은 무엇입니까?
java.util.Properties내 클래스에 허용되는 기본 속성 을 사용하여 기본 개체를 사용하고 개발자가 다른 java.util.Properties개체 를 지정하여 일부를 재정의하도록 하려고했지만이를 수행하는 좋은 방법을 찾을 수 없습니다.
의도 된 사용법은 다음과 같습니다.
Properties defaultProperties = new Properties();
defaultProperties.put("key1", "value1");
defaultProperties.put("key2", "value2");
Properties otherProperties = new Properties();
otherProperties.put("key2", "value3");
Properties finalProperties = new Properties(defaultProperties);
//
// I'd expect to have something like:
//
// finalProperties.merge(otherProperties);
//
java.util.Properties구현하는 java.util.Map인터페이스, 그리고 그렇게 할 수 단지 등의 취급 및 사용 방법이 좋아하는 putAll다른 사람의 내용을 추가합니다 Map.
그러나지도처럼 취급하는 경우 다음과 같이 매우주의해야합니다.
new Properties(defaultProperties);
복사 생성자처럼 보이지만 그렇지 않기 때문에 종종 사람들을 잡습니다 . 해당 생성자를 사용하고 다음과 같은 것을 호출하면 keySet()( Hashtable수퍼 클래스 에서 상 속됨 )의 Map메서드가 생성자에 전달 된 Properties기본 Properties개체를 고려하지 않기 때문에 빈 집합 이 생성됩니다. 기본값은 및 Properties과 같이 자체적으로 정의 된 메소드를 사용하는 경우에만 인식됩니다 .getPropertypropertyNames
따라서 두 개의 Properties 개체를 병합해야하는 경우 다음을 수행하는 것이 더 안전합니다.
Properties merged = new Properties();
merged.putAll(properties1);
merged.putAll(properties2);
이렇게하면 결과 중 하나를 "기본"속성 집합으로 임의로 레이블을 지정하는 대신보다 예측 가능한 결과를 얻을 수 있습니다.
일반적으로 나는 (내 의견으로는) Java 초기의 구현 실수 였기 때문에 (속성 에는 확장이 아니라 지연된 디자인 이었음)으로 정의 된 빈혈 인터페이스 Properties로 취급하지 않는 것이 좋습니다 . 그 자체로는 많은 옵션을 제공하지 않습니다.MapHashtableProperties
결국 파일에서 속성을 읽고 싶다고 가정하면 다음과 같이 동일한 속성 개체에 두 파일을 모두로드합니다.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("default.properties"));
properties.load(getClass().getResourceAsStream("custom.properties"));
거의 좋습니다.
Properties defaultProperties = new Properties();
defaultProperties.setProperty("key1", "value1");
defaultProperties.setProperty("key2", "value2");
Properties finalProperties = new Properties(defaultProperties);
finalProperties.setProperty("key2", "value3");
편집 : 대체 put에 의해 setProperty.
네 말이 맞아요. 그냥 putAll 메서드를 호출하면 끝입니다.
putAll () : 지정된 맵의 모든 매핑을이 해시 테이블로 복사합니다. 이러한 매핑은이 해시 테이블이 현재 지정된 맵에있는 모든 키에 대해 가지고있는 모든 매핑을 대체합니다.
Properties merged = new Properties();
merged.putAll(properties1);
merged.putAll(properties2);
2 행은 전혀 효과가 없습니다. 첫 번째 파일의 속성은 병합 된 속성 개체에 포함되지 않습니다.
참고 URL : https://stackoverflow.com/questions/2004833/how-to-merge-two-java-util-properties-objects
'IT TIP' 카테고리의 다른 글
| 간단한 삽입 문을 사용하여 바이너리 파일 데이터를 바이너리 SQL 필드에 삽입하려면 어떻게해야합니까? (0) | 2020.12.06 |
|---|---|
| 마지막 명령의 벽 시간을 Bash 프롬프트에 어떻게 넣을 수 있습니까? (0) | 2020.12.06 |
| numpy의 "isnotnan"기능이 더 비단뱀 적일까요? (0) | 2020.12.06 |
| 상대적인 URL 대신 전체 이미지 URL을 사용하도록 TinyMCE 가져 오기 (0) | 2020.12.06 |
| 언제 처음으로 뷰를 측정 할 수 있습니까? (0) | 2020.12.06 |