`

用java读取ini文件(支持中文)

    博客分类:
  • Java
阅读更多

2012-11-29

google出一个非常犀利的iniEditor: http://grepcode.com/file/repository.jboss.org/nexus/content/repositories/releases/org.rhq/rhq-core-util/3.0.0.EmbJopr4/org/rhq/core/util/IniEditor.java

 

我才写了百来行,人家的代码有上千行。我的只读,人家的还能修改,确实很强。

不过还没测试过中文,应该木有问题!

----

 

 

ini文件在日常工作中用得还是挺广泛的。在目前我手上的一个小项目之中,也用到了ini文件。而且里面存储了中文。

在网上也找了别人的代码,比如有个“由月”大神写的,我觉得写得就挺好的。

但是发现不支持中文。于是乎就自己写了一个简单的读取ini文件的方法。也在此共享出来。

欢迎大家提意见!

 

Known Issues:

1. 调用的java source file必须是UTF-8格式的。我在Eclipse3.7中,发现默认的格式为CP1252. 不支持中文。因此调用打印的结果也是乱码。

2. 第一行是section名字的话,发现无法读出来。直接略过。【我自己也不知道怎么解决。】

 

PS:进公司才发现,原来GoAgent的原创者phus就坐在我旁边,好崇拜,好幸运啊!哈哈!

向他学习!

 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Simple reader methods for ini formated file using java
 * Using UTF-8 encoding.
 * Support DBCS, such as Chinese, Japanese
 * @author Wenjun Yang
 * @email  yang.rangerwolf@gmail.com
 * 2011-10-30   
 *
 */
public class IniReader {
					// section        item     value
	private static Map<String, HashMap<String, String>> sectionsMap = new HashMap<String, HashMap<String, String>>();
					//      item    value
	private static HashMap<String, String> itemsMap = new HashMap<String, String>();
	
	private static String currentSection = "";

	/**
	 * Load data from target file
	 * @param file target file. It should be in ini format
	 */
	private static void loadData(File file) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			while ((line = reader.readLine()) != null) {
				line = line.trim();
				if("".equals(line)) continue;
				if(line.startsWith("[") && line.endsWith("]")) {
					// Ends last section
					if(itemsMap.size() > 0 && !"".equals(currentSection.trim())) {
						sectionsMap.put(currentSection, itemsMap);
					}
					currentSection = "";
					itemsMap = null;
					
					// Start new section initial
					currentSection = line.substring(1, line.length() -1);
					itemsMap = new HashMap<String, String>(); 
				} else {
					int index = line.indexOf("=");
					if(index != -1) {
						String key = line.substring(0,index);
						String value = line.substring(index + 1, line.length());
						itemsMap.put(key, value);
					}
				}
//				System.out.println(line);
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	
	
	public static String getValue(String section, String item, File file) {
		loadData(file);
		
		HashMap<String, String> map = sectionsMap.get(section);
		if(map == null) {
			return "No such section:" + section;
		}
		String value = map.get(item);
		if(value == null) {
			return "No such item:" + item;
		}
		return value;
	}
	
	public static String getValue(String section, String item, String fileName) {
		File file = new File(fileName);
		return getValue(section, item, file);
	}
	
	public static List<String> getSectionNames(File file) {
		List<String> list = new ArrayList<String>();
		loadData(file);
		Set<String> key = sectionsMap.keySet();
        for (Iterator<String> it = key.iterator(); it.hasNext();) {
        	list.add(it.next());
        }
		return list;
	}
	
	public static Map<String, String> getItemsBySectionName(String section, File file) {
		loadData(file);
		return sectionsMap.get(section);
	}
}

 

分享到:
评论
4 楼 RangerWolf 2013-10-23  
yxc023 写道
静态成员变量.....

大神,静态成员变量怎么了? 求指导~~~
3 楼 yxc023 2013-09-10  
静态成员变量.....
2 楼 RangerWolf 2013-07-06  
woundsofcloud 写道
很好的一个例子。但是不知道为什么,最后一个section的值获取不到,总是会报空指针异常,但是debug时却发现sectionsMap中有值存在,头痛。。。。  还有一个解决中文乱码的问题:1,将文件保存为utf-8格式。2,将36行的reader = new BufferedReader(new FileReader(file));  改为reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "gbk"));



自己写的时候 确实发现很多很多需要解决的问题~
后来发现有人家写好的 而且后来在自己的各种项目中都在使用的代码 非常推荐:
http://grepcode.com/file/repository.jboss.org/nexus/content/repositories/releases/org.rhq/rhq-core-util/3.0.0.EmbJopr4/org/rhq/core/util/IniEditor.java


就在我的博客的第一句话~
1 楼 woundsofcloud 2013-01-31  
很好的一个例子。但是不知道为什么,最后一个section的值获取不到,总是会报空指针异常,但是debug时却发现sectionsMap中有值存在,头痛。。。。  还有一个解决中文乱码的问题:1,将文件保存为utf-8格式。2,将36行的reader = new BufferedReader(new FileReader(file));  改为reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "gbk"));

相关推荐

Global site tag (gtag.js) - Google Analytics