小白刚毕业入职,最近空闲时间看了本黄勇先生著作的《从零开始写Java Web框架》,感觉整体比较通俗易懂,适合新人学习,不过小白基础较差,虽然作者的写的很清晰,但还是有个别部分没有理解,防止遗忘,根据书中解释与自己的理解,记录在博客,也便于日后温故知新,博客不对的地方,希望大神们指点
当前流行的各种框架,多数框架把一些属性配置,放在.properties文件中,比如数据库配置文件、日志配置文件等。其好处是与源码解耦,配置文件需要做出修改时,可以不用修改编译源码。.properties类型的配置文件读取需要用到Properties类,看其源码,可以知道其继承了HashTable,也就是说Propertiies类说白了就是个容器,理解了这一点,就发现其使用非常简单。
.properties类型的文件读取,直接调用Properties类的load方法即可
public static Properties loadProps(String fileName) {
Properties props = null;
InputStream is = null;
try {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
if (is == null) {
throw new FileNotFoundException(fileName + " file is not found");
}
props = new Properties();
props.load(is);
} catch (IOException e) {
LOGGER.error("load properties file failure", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOGGER.error("close input stream failure", e);
}
}
}
return props;
}
刚说Properties extends Hashtable<Object,Object>,所以从配置文件中读取的可以直接使用getProperty(key)来获取,比如
public static String getString(Properties props, String key, String defaultValue) {
String value = defaultValue;
if (props.containsKey(key)) {
value = props.getProperty(key);
}
return value;
}
从文件中获取了该属性值后,就可以进行类型转换,比如该属性值为int型,则可以对String类型的value值进一步转换为int类型,比如
public static int getInt(Properties props, String key, int defaultValue) {
int value = defaultValue;
if (props.containsKey(key)) {
value = Integer.parseInt(props.getProperty(key));
}
return value;
}
类似的可以转换为其他基本类型的值,熟悉了.perperties文件的读取之后,日后在开发自己的框架时,就可以学习借鉴