java 比properties好的文件读取方法

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;
	}
}


----------------------------------------------------------------------------------------------------


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值