造轮子——配置文件读取工具

因为自己做一些Demo的时候,数据库连接池等等使用的很频繁,而我又不喜欢将配置信息写入源码,就一直使用读取配置文件的方法,并没有使用XDOM解析XML,太麻烦了,经常使用properties,轻巧便捷,但是为了更省时,就将其封装成一个读取配置文件的工具。

package 配置文件读取;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class ConfigFileLoad {
	/*
	 * 该类为配置文件读取,因为配置数据库连接池,线程池等,习惯 将键值对写在配置文件中,通过properties进行读取, 特此进行封装一个类,直接提供读取方法
	 */
	private static Properties ConfigerFileReader = new Properties();

	/*
	 * 将该类设置为单例模式,防止出现过多今天遍历导致GC失败 出现内存溢出的情况
	 */
	// 私有化构造函数
	private ConfigFileLoad() {
	};

	// 私有化内部对象
	private static ConfigFileLoad ConfigFileLoad = null;

	// 对外暴露方法
	public static ConfigFileLoad getConfigFileLoadObject() {
		if (ConfigFileLoad == null) {
			return new ConfigFileLoad();
		}
		return ConfigFileLoad;
	}
	/*
	 * 其中用了大量的try—catch语法块,目的防止出现异常,并能通过这些最后实现关闭流
	 */
	public boolean getConfigFile(String url) {
		// 获取文件输入流
		/*
		 * 在这里并没有使用ClassLoader的加载方式,因为希望该类可以复用
		 * 能够读取任意地方的配置文件,所以在这里我们所要求读取的配置文件Url
		 * 需要填写为全路径String值
		 */
		FileInputStream in = null;
		boolean isSuccess = true;
		try {
			in = new FileInputStream(url);
			// 配置ConfigerFileReader,进行加载
			ConfigerFileReader.load(in);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("配置文件为找到,请检查Url路径是否正确");
			isSuccess = false;
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("读取发生异常,请检查日志");
			isSuccess = false;
			e.printStackTrace();
		}
		//最后将流进行关闭
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("输入流未关闭,请检查日志");
			e.printStackTrace();
		}
		return isSuccess;
	}

	/*
	 * 读取操作我们打算使用重载来实现多种参数配置
	 * 支持String[]  String
	 * 内部提供转换器来进行转换
	 */
	public String read(String Key) {
		String Value = null;
		Value = ConfigerFileReader.getProperty(Key);
		
		if(Value == null) {
			System.out.println("未读取到该参数,无法获取值");
			return null;
		}
		return Value;
	}
	
	public String[] read(String[] Key) {
		int length = Key.length;
		//获得与值相同长度的数组
		String[] Values = new String[length];
		/*
		 * 直接内部进行遍历,并对为读取到的信息进行反馈后手动填写
		 */
		for(int i = 0;i<length;i++) {
			if(Values[i] != null) {
				Values[i] = ConfigerFileReader.getProperty(Key[i]);
			}else {
				System.out.println("Key值为"+Key[i]+"的数据未能获取,请检查配置文件");
			}
		}
		return Values;
	}
	
}

猜你喜欢

转载自blog.csdn.net/weixin_41582192/article/details/81701973