工具:idea
jdk:1.8
缘由:一下午在实现一个计算器的小栗子,最终目的是将一切常量封装,对应算法抽离,实现高内聚低耦合效果。例子中用到了策略模式、简单工厂加反射,并且将运算符号常量一键值对的形式放在了配置文件中,分别对应不同的算法类名称。
那么在工厂中怎样读取到配置文件中对应的常量呢?
下面将提供三个方法:
一、基于InputStream读取配置文件信息
public static CounterInterface counterInterface(String key) throws Exception {
// 创建Properties对象,用于读取配置文件
Properties props = new Properties();
//我这里用的是绝对路径,相对路径找不到配置文件,不清楚什么原因
//或者可以用InputStream ips = counterInterface.class.getClassLoader().getResourceAsStream(文件路径)
InputStream ips = new FileInputStream("D:\\allproject\\Counter\\src\\main\\resources\\config.properties");
// 由于配置文件中可能存在中文乱码问题,应用reader类进行转换后解决
Reader inStream = new InputStreamReader(ips, "UTF-8");
props.load(inStream);
//getProperty用于获取properties中 对应键的键值,应用反射 ,实例化出键值对应的类 的对象
CounterInterface counterInterface= (CounterInterface) Class.forName(props.getProperty(key)).newInstance();
return counterInterface;
}
二、通过spring中的 PropertiesLoaderUtils工具类进行获取:
public static CounterInterface counterInterface(String key) throws Exception {
Properties properties = new Properties();
try {
properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
String res=new String(properties.getProperty(key).getBytes("iso-8859-1"), "gbk");
} catch (IOException e) {
e.printStackTrace();
}
//getProperty用于获取properties中 对应键的键值,应用反射 ,实例化出键值对应的类 的对象
CounterInterface counterInterface= (CounterInterface) Class.forName(res).newInstance();
return counterInterface;
}
便利取值:
Properties properties = new Properties();
try {
properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
//遍历取值
Set<Object> objects = properties.keySet();
for (Object object : objects) {
System.out.println(new String(properties.getProperty((String) object).getBytes("iso-8859-1"), "gbk"));
}
} catch (IOException e) {
e.printStackTrace();
}
三、通过 java.util.ResourceBundle 类读取:
private static void readProperty3() {
ResourceBundle resourceBundle = ResourceBundle.getBundle("code");
//遍历取值
Enumeration enumeration = resourceBundle.getKeys();
while (enumeration.hasMoreElements()) {
try {
String value = resourceBundle.getString((String) enumeration.nextElement());
System.out.println(new String(value.getBytes("iso-8859-1"), "gbk"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}