我们知道,在做项目时,为了提高项目的扩展性是不能将参数写死的,所以,将值写入属性文件、xml文件等就成为了必然。那我们应该怎么获取当中的值呢?这个问题以前一直困恼着我,当然,那是很久以前的事情啦。我也相信肯定有很多人是不知道的,现在,我就分享一下我的写法吧:
1、在定义类的相关成员变量,如下:
public static Properties config = new Properties();
private static String config_path = "fileUpload.properties";
private static Hashtable<String, Properties> instanceCache = new Hashtable<String, Properties>();
2、创建两个方法,一个为获取属性文件的对象,另一个为加载属性文件的对象,分别如下:
/**
* 加载配置文件
* @return
*/
public Properties loadConfig(String propName){
InputStream in = getClass().getClassLoader().getResourceAsStream(config_path);
try {
config.load(in);
instanceCache.put(propName, config);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return config;
}
/**
* 获取配置文件
* @param propFileName
* @return
*/
private static Properties getProperty(String propFileName) {
if (instanceCache.containsKey(propFileName)) {
return (Properties) instanceCache.get(propFileName);
} else {
return null;
}
}
3、编写主函数,对属性文件进行判断,如下:
Properties config = getProperty(config_path);
if (config == null) {
config = loadConfig(config_path);
}
4、通过属性文件中的name获取相应的value,如下:
String tempDir = config.getProperty("tempDir");//存储图片的临时目录
OK,大功告成,有兴趣的童鞋自己动手试试吧!!!