By Alvin Alexander. Last updated: June 4, 2016
At the moment I can't remember why I wrote this method to read a Java properties file and return it as a Map of key/value pairs ... but if for some reason you happen to need a Java method that reads a properties file and returns the contents as a Map, here's some free source code for you:
/**
* Reads a "properties" file, and returns it as a Map
* (a collection of key/value pairs).
*
* @param filename The properties filename to read.
* @param delimiter The string (or character) that separates the key
* from the value in the properties file.
* @return The Map that contains the key/value pairs.
* @throws Exception
*/
public static Map<String, String> readPropertiesFileAsMap(String filename, String delimiter)
throws Exception
{
Map<String, String> map = new HashMap();
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null)
{
if (line.trim().length()==0) continue;
if (line.charAt(0)=='#') continue;
// assumption here is that proper lines are like "String : http://xxx.yyy.zzz/foo/bar",
// and the ":" is the delimiter
int delimPosition = line.indexOf(delimiter);
String key = line.substring(0, delimPosition-1).trim();
String value = line.substring(delimPosition+1).trim();
map.put(key, value);
}
reader.close();
return map;
}
As I write this I'm still struggling to think of why I wrote a method to read a properties file and return it as a Java Map, but if I ever remember why I did this, I'll be glad to share my reasoning here, lol. In the meantime, if it serves as a Java Map example, I hope that is helpful.
As a final note, if you are looking for an example of how to normally read a Java properties file, here's a link to my "Java properties file example".

