public final class INI {
private final static Map<String, Map<String, Object>> iniFile = new HashMap<String, Map<String, Object>>();
private INI(){};
final public static synchronized void setValue(String section, String key,Object value) {
Map<String,Object> sectionMap =iniFile.get(section);
if(sectionMap==null){
sectionMap = new HashMap<String,Object>();
iniFile.put(section, sectionMap);
}
sectionMap.put(key, value);
}
final public static synchronized Object getValue(String section, String key) {
Object obj = null;
Map<String, Object> item = iniFile.get(section);
if (item != null) {
obj = item.get(key);
}
return obj;
}
//加载ini文件
final public static synchronized void load(String path) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(path));
String str = reader.readLine();
String section = null;
while (str != null) {
if (str.startsWith("[")&& str.endsWith("]")) { //读取ini文件模块头
Map<String, Object> itemMap = new HashMap<String, Object>();
section = str.substring(1, str.length() - 1);//获取ini文件头
// System.out.println(section);
iniFile.put(section, itemMap);//把ini文件头放入map中
}else if(str.indexOf("=")>0){
Map<String, Object> itemMap = iniFile.get(section);//获取对应的ini文件头 并读取key 和 value
String key = str.substring(0, str.indexOf("="));
String value = str.substring(str.indexOf("=") + 1);
itemMap.put(key, value);
}
str = reader.readLine();
}
reader.close();
}
final public static synchronized void write(String path) throws IOException {
StringBuffer sb = new StringBuffer("");
String crlf=System.getProperty("line.separator");//分隔符
for (String section : iniFile.keySet()) {
sb.append("[").append(section).append("]").append(crlf);
Map<String, Object> map = iniFile.get(section);
Set<String> keySet = map.keySet();
for (String key : keySet) {
sb.append(key).append("=").append(map.get(key)).append(crlf);
}
}
/* File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}*/
BufferedWriter writer = new BufferedWriter(new FileWriter(path));
writer.write(sb.toString());
writer.flush();
writer.close();
}
}
一个读写ini文件属性的例子
最新推荐文章于 2019-07-21 23:01:49 发布