Populating a HashMap with entries from a properties file

前端 未结 5 1180
南笙
南笙 2020-12-14 08:45

I want to populate a HashMap using the Properties class.
I want to load the entries in the .propeties file and then copy it into

相关标签:
5条回答
  • 2020-12-14 09:26

    Java 8 Style:

    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())));
    
    0 讨论(0)
  • 2020-12-14 09:33

    If I understand correctly, each value in the properties is a String which represents an Integer. So the code would look like this:

    for (String key : properties.stringPropertyNames()) {
        String value = properties.getProperty(key);
        mymap.put(key, Integer.valueOf(value));
    }
    
    0 讨论(0)
  • 2020-12-14 09:42

    Use .entrySet()

    for (Entry<Object, Object> entry : properties.entrySet()) {
        map.put((String) entry.getKey(), (String) entry.getValue());
    }
    
    0 讨论(0)
  • 2020-12-14 09:44
    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 讨论(0)
  • 2020-12-14 09:45

    you can use the below Method to load the property file in a map

    public static Map<String, String> getProperties(String filePropertyFile){
            Properties getProperties = new Properties();
            FileInputStream inputStream = null;
            HashMap<String, String> propertyMap = new HashMap<String, String>();
            try {
                inputStream = new FileInputStream(filePropertyFile);
                getProperties.load(inputStream);
                propertyMap.putAll((Map) getProperties);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return propertyMap;
        }
    

    Unit Test:

    @Test
    public void getPropertiesTest()
        String outputOmJarArrayAttributesPath = System.getProperty("user.dir") + "/src/main/resources/OutputOmJarArrayAttributes.properties";
        System.out.println(PropertyFileUtils.getProperties(outputOmJarArrayAttributesPath));;
        }
    
    0 讨论(0)
提交回复
热议问题