properties不支持中文,必须转码,让可读性很差。所以随便写了一个ini文件,规则还是一样,支持#注释,这个工具类把所有的配置都放到map里返回。
先看效果!
ini文件内容:
=====================================================
#不带[section]
aa=123
bB=我们
#带section
[abc]
cc=wejefdlfjdsk
Dd=kdjfsfl
=====================================================
运行结果:
=====================================================
{aa=123, bB=我们, abc.cc=wejefdlfjdsk, abc.Dd=kdjfsfl}
=====================================================
代码如下:
--------------------------------------------------------------------------------
package menu;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
/**
* 读取ini文件,支持中文
*
* @author qichun
*
*/
public class IniUtil {
private static Map<String, Object> iniMap = new HashMap<String, Object>();
public static Map<String, Object> readIni(String filePath) {
if (!iniMap.isEmpty())
iniMap.clear();
try {
BufferedReader bufReader = new BufferedReader(new FileReader(filePath));
String strLine = "", Section = "";
int firstLeftSquareBrackets = 0, firstRightSquareBrackets = 0;
while ((strLine = bufReader.readLine()) != null) {
if (strLine.startsWith("#")){
continue;
}
strLine = strLine.trim();
firstLeftSquareBrackets = strLine.indexOf("[");
firstRightSquareBrackets = strLine.indexOf("]");
if (firstLeftSquareBrackets >= 0 && firstRightSquareBrackets >= 0
&& firstLeftSquareBrackets < firstRightSquareBrackets) {
Section = strLine.substring(firstLeftSquareBrackets + 1, firstRightSquareBrackets);
} else {
if ("".equals(strLine)){
continue;
}
int index = 0;
index = strLine.indexOf("=");
String Key = strLine.substring(0, index).trim();
String Value = strLine.substring(index + 1).trim();
String hashKey = "";
if (!"".equals(Section)) {
hashKey = Section + "." + Key;
} else {
hashKey = Key;
}
iniMap.put(hashKey, Value);
}
}
bufReader.close();
} catch (Exception e) {
System.out.println("读取配置文件发生错误。" + e.getMessage());
}
return iniMap;
}
}
----------------------------------------------------------------------------------------------------