2013-05-02 4 views
11

Properties 클래스를 사용하여 HashMap을 채우려고합니다. .propeties 파일의 항목을로드 한 다음 HashMap에 복사하고 싶습니다.속성 파일의 항목으로 HashMap 채우기

이전에 속성 파일로 HashMap을 초기화했지만 지금은 HashMap을 이미 정의했으며 생성자에서만 초기화하려고합니다.

이전 방법 :

Properties properties = new Properties(); 
try { 
properties.load(ClassName.class.getResourceAsStream("resume.properties")); 
} 
catch (Exception e) { 
} 
HashMap<String, String> mymap= new HashMap<String, String>((Map) properties); 

하지만 지금은 내가

public class ClassName { 
HashMap<String,Integer> mymap = new HashMap<String, Integer>(); 

public ClassName(){ 

    Properties properties = new Properties(); 
    try { 
     properties.load(ClassName.class.getResourceAsStream("resume.properties")); 
    } 
    catch (Exception e) { 

    } 
    mymap = properties; 
    //The above line gives error 
} 
} 

가 어떻게이 속성을 할당 할이 여기에 HashMap에 반대 있나요?

답변

20

올바르게 이해하면 속성의 각 값은 정수를 나타내는 String입니다. 그래서 코드는 다음과 같습니다

for (String key : properties.stringPropertyNames()) { 
    String value = properties.getProperty(key); 
    mymap.put(key, Integer.valueOf(value)); 
} 
+3

같이 getResourceAsStream를 사용할 때 ** 널 (null)을 받고있어 * *, 아마도 클래스 패스 밖에서 파일을 찾고 있기 때문일 것이다. 따라서 절대 파일 경로를 읽으려면 다음을 할 수 있습니다 : \t \t'File file = new File ("absolute/file/path/resume.properties"); \t \t \t FileInputStream fileInputStream = 새 FileInputStream (파일); \t \t \t properties.load (fileInputStream); \t \t \t fileInputStream.close(); ' –

14

사용 .entrySet()

for (Entry<Object, Object> entry : properties.entrySet()) { 
    map.put((String) entry.getKey(), (String) entry.getValue()); 
} 
1
public static Map<String,String> getProperty() 
    { 
     Properties prop = new Properties(); 
     Map<String,String>map = new HashMap<String,String>(); 
     try 
     { 
      FileInputStream inputStream = new FileInputStream(Constants.PROPERTIESPATH); 
      prop.load(inputStream); 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
      System.out.println("Some issue finding or loading file....!!! " + e.getMessage()); 

     } 
     for (final Entry<Object, Object> entry : prop.entrySet()) { 
      map.put((String) entry.getKey(), (String) entry.getValue()); 
     } 
     return map; 
    } 
+0

몇 가지 설명을 제공해 주시겠습니까? – Cherniv

+0

키와 값을 가진 맵에서 속성 파일을 채우기 만하면됩니다. GetProperty()는 키와 값으로 Map을 반환합니다. getProperty(). get ("key")와 같이하면 값에 간단하게 액세스 할 수 있습니다. –

2

자바 8 스타일 : 경우

Properties properties = new Properties(); 
// add some properties here 
Map<String, String> map = new HashMap(); 

map.putAll(properties.entrySet().stream() 
        .collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()))); 
관련 문제