第一接触ini配置文件,这里记录两种读取方式:
- 通过Properties读取ini文件
这种方式网上使用的最多也最方便,不过读取顺序会有变化。
/**
* 最简单的读取ini方法 但是读取的顺序会变化
*
* @param file
* @return
* @throws Exception
*/
public String read(String file) throws Exception {
Properties pro = new Properties();
StringBuffer sb = new StringBuffer();
InputStream in = new BufferedInputStream(new FileInputStream(file));
pro.load(in);
Set keyValue = pro.keySet();
for (Iterator it = keyValue.iterator(); it.hasNext();) {
String key = (String) it.next();
sb.append(key + ":" + pro.get(key) + "\n");
// System.out.println(key + " "+ pro.get(key));
}
return sb.toString();
}
- 自己写的读取方式,其中将ini注解变成#的方式输出,并根据ini每个节划分,组合“节_key”的方式输出。
private static HashMap<String, String> itemsMap = new HashMap<String, String>();
private static String currentSection = "";//节名称
/**
* 读取ini 文件
* @param file 文件路径
* @return String 返回所有内容
* @throws Exception
*/
public String read2(String file) throws Exception {
StringBuffer sb = new StringBuffer();
BufferedReader bf = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "GB2312"));
String line = null;
while ((line = bf.readLine()) != null) {
line = line.trim();
if ("".equals(line))
continue;
if (line.startsWith("[") && line.endsWith("]")) {
currentSection = line.substring(1, line.length() - 1);
sb.append(currentSection+"\r\n");
}else if(line.startsWith(";")){
String str = "#"+line.substring(1);
sb.append(str+"\r\n");
}else {
int index = line.indexOf("=");
if (index != -1) {
String key = currentSection + "_"
+ line.substring(0, index);
String value = line.substring(index + 1, line.length());
itemsMap.put(key, value);
sb.append(key+"="+value+"\r\n");
}
}
}
return sb.toString();
}
暂时总结这一点点,后续用到在添加。