您的位置:首页 > 编程语言 > Java开发

javaWeb加载Properties文件

2016-05-11 16:57 405 查看
public static Properties loadProps(String fileName) {
Properties props = null;
InputStream is = null;
try {
//注意:main/java、main/resources、test/java、test/resources这四个目录都是classpath的根目录
//,当运行单元测试时,遵循“就近原则”,即优先从test/java、test/resources加载类或读取文件
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;
}


代码中的注释是在做有关单元测试的项目中写的,附上下图好理解。如果config.properties就在resources文件夹下,fileName="config.properties";如果config.properties在config文件夹下,fileName="config/config.properties"

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: