John Main Logo

John Main

Code. Design. Hosting. Maintenance.

27
Aug '11

Read a config file, parse it and add key/value pairs to a hashmap

import java.io.*;
import java.util.HashMap;

/**
* @param configFile the location of the configuration file
* @return the produced HashMap
*/
public HashMap importConfig(String configFile) {
	HashMap config = new HashMap;

	try {
		BufferedReader bufRead = new BufferedReader(new FileReader(configFile));

		while(bufRead.ready()) {
			String line = bufRead.readLine();

			if(!line.startsWith("#") && line.indexOf("=") != -1) {
				//Trim out whitespace, explode at equals and put key/value pairs into the config HashMap
				int splitPos = line.indexOf("=");
				String key = line.substring(0, splitPos).trim();
				String value = line.substring(splitPos+1, line.length()).trim();

				if(!key.equals("") && !value.equals("")) {
					config.put(key, value);
				}
			}
		}

		bufRead.close();
	}
	catch (FileNotFoundException e) {
		System.out.println(e.getMessage());
	}
	catch (IOException e) {
		System.out.println(e.getMessage());
	}

	return config;
}