web工程读取配置文件的几种方式
配置文件配置在WebContent目录下
第一种:获取资源在tomcat里面的绝对路径
- 获取WebContent/properties/config.properties文件信息
通过ServletContext获取绝对路径
context.getRealPath("");
String path = context.getRealPath("properties/config.properties");
第二种:获取资源的流对象
- 获取WebContent/properties/config.properties文件信息
InputStream is = context.getResourceAsStream("properties/config.properties");
prop.load(is);
第三种:通过classLoader()
- 获取WebContent/properties/config.properties文件信息
- 使用getClassLoader()的根目录是\WEB-INF\classes
- …/…/才是WebContent目录
InputStream is = this.getClass().getClassLoader()
.getResourceAsStream("../../properties/config.properties");
prop.load(is);