Java読み込みiniファイル
3649 ワード
iniファイルは次のようになります.
[module_0] key-num = 2 redis-key = mon_login redis-node = 192.168.144.119:6379|192.168.144.120:6379 polling = 1 [module_1] key-num = 2 redis-key = mon_register redis-node = 192.168.144.119:6379|192.168.144.120:6379 polling = 1
[module_0] key-num = 2 redis-key = mon_login redis-node = 192.168.144.119:6379|192.168.144.120:6379 polling = 1 [module_1] key-num = 2 redis-key = mon_register redis-node = 192.168.144.119:6379|192.168.144.120:6379 polling = 1
public class LoadConfig {
private static final Logger logger = Logger.getLogger(LoadConfig.class);
private BufferedReader reader = null;
private Map<String,Map<String, String>> map = null;
private String currentSection = null;
/**
*
* @param path
*/
public LoadConfig(String path) throws IOException{
map = new HashMap<String, Map<String,String>>();
reader = new BufferedReader(new FileReader(path));
read(reader);
logger.info("load config file success.");
reader.close();
}
/**
*
* @param reader
* @throws IOException
*/
private void read(BufferedReader reader) throws IOException {
String line = null;
while((line=reader.readLine())!=null) {
parseLine(line);
}
}
/**
*
* @param line
*/
private void parseLine(String line) {
line = line.trim();
//
if(line.matches("^\\#.*$")) {
return;
}else if (line.matches("^\\[\\S+\\]$")) {
// section
String section = line.replaceFirst("^\\[(\\S+)\\]$","$1");
addSection(map,section);
}else if (line.contains("=")) {
// key ,value
int i = line.indexOf("=");
String key = line.substring(0, i).trim();
String value =line.substring(i + 1).trim();
addKeyValue(map,currentSection,key,value);
}
}
/**
* Key Value
* @param map
* @param currentSection
* @param key
* @param value
*/
private void addKeyValue(Map<String, Map<String,String>> map,
String currentSection,String key, String value) {
if(!map.containsKey(currentSection)) {
return;
}
Map<String,String> childMap = map.get(currentSection);
if(!childMap.containsKey(key)) {
childMap.put(key, value);
}
}
/**
* Section
* @param map
* @param section
*/
private void addSection(Map<String, Map<String,String>> map,
String section) {
if (!map.containsKey(section)) {
currentSection = section;
Map<String,String> childMap = new HashMap<String,String>();
map.put(section, childMap);
}
}
/**
* Section
* @param section
* @param key
* @return
*/
public String get(String section,String key){
if(map.containsKey(section)) {
return get(section).containsKey(key) ?
get(section).get(key): null;
}
return null;
}
/**
* Section
* @param section
* @return
*/
public Map<String, String> get(String section){
return map.containsKey(section) ? map.get(section) : null;
}
/**
*
* @return
*/
public Map<String, Map<String, String>> get(){
return map;
}
/**
*
* @throws IOException
*/
public void close() throws IOException{
reader.close();
}
}