J2SE配置文件读取工具

为下周的实习做准备,有读取ini配置文件的需求,编写了这个类。

这个版本只实现了读取功能,以后可能继续实现写入功能

首先是异常类

package configFile;


/**
 * 配置文件格式错误异常
 * @author Administrator
 *
 */
public class ConfigFileFormatException extends Exception {

	private static final long serialVersionUID = -8622815453009039638L;

}
 
然后是配置文件操作类
package configFile;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.jar.Attributes;

/**
 * 配置文件读取
 * 
 * 实现在J2SE下读取ini配置文件,配置文件的格式如下
 * 
 * #注释
 * [段名]
 * 变量名=变量值
 * 变量名="变量值"
 * 
 * 1、使用#表示注视行
 * 2、段名不指定则为默认段
 * 3、变量名允许使用的字符有[0-9a-zA-Z_-]
 * 4、变量值如果中间有空格,请使用引号,如"Variable value"
 * 
 * @author 石莹
 * @version 1.0
 * 
 */
public class ConfigFile {
	
	//DEBUG
	private final boolean DEBUG = false;

	//保存读入的数据
	private Attributes data = new Attributes();
	
	/**
	 * 获得一个变量的值(默认段)
	 * @param name 要获得的变量名
	 * @return 获得的值
	 */
	public String getAttribute(String name) {
		return data.getValue("Default-" + name);
	}
	
	/**
	 * 获得一个变量的值
	 * @param pageName 要获得的变量的段名(若为null,则表示使用默认段)
	 * @param variableName 要获得的变量名
	 * @return 获得的值
	 */
	public String getAttribute(String pageName, String variableName) {
		if (pageName == null) pageName = "Default";
		return data.getValue(pageName + "-" + variableName);
	}
	
	/**
	 * 读取配置文件
	 * @param filename	要读取的文件名
	 * @throws IOException	如果打开文件发生IO错误,抛出异常
	 * @throws ConfigFileFormatException	如果配置文件格式错误,抛出异常
	 */
	public void readFile(String filename) throws IOException, ConfigFileFormatException {
		
		//获得文件的读入流
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
		
		//段名
		String pageName = "Default";	
		
		//处理需要的StringBuffer
		StringBuffer buffer = new StringBuffer();
		
		//每次循环处理一行
		String lineStr = null;
		while ((lineStr = br.readLine()) != null) {
			//忽略字符串前导空白和尾部空白
			lineStr = lineStr.trim();
			
			//如果是空行,跳过
			if (lineStr.length() == 0)
				continue;
			
			//如果是注视行,跳过
			if (lineStr.charAt(0) == '#')
				continue;
			
			//如果是段标记,更新当前段段名
			if (lineStr.charAt(0) == '[') {
				//清空buffer
				buffer.delete(0, buffer.length());
				//读取段名到buffer中
				int n = 1;
				while (lineStr.charAt(n) != ']') {
					buffer.append(lineStr.charAt(n++));
				}
				if (buffer.length() != 0) {
					pageName = buffer.toString().trim();
				}
				continue;
			}
			
			//读取变量名
			String name = null;
			//清空buffer
			buffer.delete(0, buffer.length());
			//读取变量名到buffer中
			int index = 0;
			while (lineStr.charAt(index) != '=') {
				buffer.append(lineStr.charAt(index++));
			}
			if (buffer.length() != 0) {
				name = buffer.toString().trim();
			} else {
				throw new ConfigFileFormatException();
			}
			
			//读取值
			index ++;	//跳过字符=
			String value = null;
			//清空buffer
			buffer.delete(0, buffer.length());
			//开始读取值
			while (lineStr.charAt(index) == ' ')
				index++;
			if (lineStr.charAt(index) == '"') {
				//如果第一个字符是",那么根据规则使用"作为结束符
				index++;
				//如果字符串结束或找到结束符,循环结束
				while (index < lineStr.length() &&
						lineStr.charAt(index) != '"') {
					buffer.append(lineStr.charAt(index++));
				}
				if (index < lineStr.length()) {
					//如果当前字符串游标合法,说明找到了结束符",查找有效
					value = buffer.toString().trim();
				} else {
					//否则,抛出格式错误异常
					throw new ConfigFileFormatException();
				}
			} else {
				//否则,使用第一个不是[a,z],[A,Z],[0~9]的字符作为结束符
				while (index < lineStr.length() && 
						((lineStr.charAt(index) >= 'a' &&  lineStr.charAt(index) <= 'z') ||
								(lineStr.charAt(index) >= 'A' &&  lineStr.charAt(index) <= 'Z') ||
								(lineStr.charAt(index) >= '0' &&  lineStr.charAt(index) <= '9') ||
								lineStr.charAt(index) == ' ')) {
					buffer.append(lineStr.charAt(index++));
				}
				value = buffer.toString().trim();
			}
			
			//保存读取的值映射
			try {
				data.put(new Attributes.Name(pageName + "-"+ name), value);
			} catch (Exception e) {
				throw new ConfigFileFormatException();
			}
			
			//debug
			if (DEBUG)
				System.out.println(pageName + "-"+ name + " = " + value);////////
		}
	}
}

测试

在c盘根目录下存放一个c.ini的配置文件,文件内容如下

test = def

[page]
test = "page test"

使用下面的程序测试

import java.io.IOException;

import configFile.ConfigFile;
import configFile.ConfigFileFormatException;



public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ConfigFile cf = new ConfigFile();
		
		try {
			cf.readFile("c:\\c.ini");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ConfigFileFormatException e) {
			e.printStackTrace();
		}
		
		System.out.println(cf.getAttribute("test"));
		System.out.println(cf.getAttribute("page", "test"));
	}
}
输出结果

def
page test

posted @ 2010-09-10 21:13  石莹  阅读(478)  评论(0编辑  收藏  举报