Skip to content

Instantly share code, notes, and snippets.

@2sbsbsb
Created March 28, 2013 04:46
Show Gist options
  • Save 2sbsbsb/5260711 to your computer and use it in GitHub Desktop.
Save 2sbsbsb/5260711 to your computer and use it in GitHub Desktop.
package util.text;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/*-
*
* Advantage
* 1. It can read any config files of any format (csv, properties file or any text files).
* 2 Format can be
* 2.a keys = values1, values2, values3
* 2.b keys, values1, values2, values3
* 3. keys with space also works
* 4. One key multiple values
* 5. Comment line starts with #. Even this can be made configuration
* 6. The order of the keys is maintained.
* 7. The order of the values for any given key is also maintained.
*/
public class ConfigFileReader {
private final String path;
private final String keyValueSeparation;
private final String valueSeparation;
public final String COMMENT_LINE_STATRTS_WITH = "#";
/**
* @param path
* @param keyValueSeparation
* @param valueSeparation
*/
public ConfigFileReader(String path, String keyValueSeparation, String valueSeparation) {
this.path = path;
this.keyValueSeparation = keyValueSeparation;
this.valueSeparation = valueSeparation;
}
/**
* @param path
* @return
* @throws IOException
*/
public Map<String, List<String>> readkeyValues() throws IOException {
// LinkedHashMap retains the order too
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
BufferedReader br = null;
try {
FileInputStream fstream = new FileInputStream(path);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File line by line
while ((strLine = br.readLine()) != null) {
if (!strLine.trim().equalsIgnoreCase("")) {
if (strLine.startsWith(COMMENT_LINE_STATRTS_WITH)) {
continue;
}
String[] keyValues = strLine.split(keyValueSeparation);
String key = keyValues[0].trim();
StringBuilder valuesBuilder = new StringBuilder();
if (keyValues.length > 1) {
for (int i = 1; i < keyValues.length; i++) {
valuesBuilder.append(keyValues[i]);
valuesBuilder.append(valueSeparation);
}
}
String values = valuesBuilder.toString();
String[] multipleValues = values.split(valueSeparation);
List<String> nultipleV = new ArrayList<String>();
for (String v : multipleValues) {
if (!v.trim().equalsIgnoreCase("")) {
nultipleV.add(v.trim());
}
}
map.put(key, nultipleV);
}
}
} finally {
br.close();
}
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment