Friday, May 13, 2016

Convert All data from Properties to a Hash Map In Java


Code Snippet :

/** The propertied values. */
       static Map<String,String> propertiedValues = new HashMap<String, String>();
       static{
         try {
              propertiedValues = getPropertiesAsMap(MESSAGE_PROPERTIES_PATH);
              System.out.println("The Size of the propertiedValues map is "+propertiedValues.size());
         } catch (FileNotFoundException fileNotFoundException) {
              fileNotFoundException.printStackTrace();
         } catch (IOException ioException) {
              ioException.printStackTrace();
         }
       }
      
       /**
        * Gets the properties as map.
        *
        * @param propertyFilePath the property file path
        * @return the properties as map
        * @throws FileNotFoundException the file not found exception
        * @throws IOException Signals that an I/O exception has occurred.
        */
       public static Map<String,String> getPropertiesAsMap(String propertyFilePath) throws FileNotFoundException, IOException{
         Properties properties = new Properties();
         Map<String,String> mapOfValues = new HashMap<String, String>();
         properties.load(new FileInputStream(propertyFilePath));
         for (String key : properties.stringPropertyNames()) {
           String value = properties.getProperty(key);
           mapOfValues.put(String.valueOf(key.trim()),value.trim());
         }
         return mapOfValues;
       }

No comments:

Post a Comment