servletContext对象获取web工程下资源文件的三种方式

这里以获取config.properties文件为例

第一种使用getRealPath()方法

ServletContext context = getServletContext();
String realPath = context.getRealPath("file/config.properties");
Properties properties = new Properties();
FileInputStream inputStream = new FileInputStream(realPath);
properties.load(new InputStreamReader(inputStream));
String name = properties.getProperty("name");

第二种使用getResourceAsStream()方法

ServletContext context = getServletContext();
Properties properties = new Properties();
InputStream asStream = context.getResourceAsStream("file/config.properties");
properties.load(new InputStreamReader(asStream));
String name = properties.getProperty("name");

注意: 此种方式只能获取项目根目录下的资源流对象,class文件的流对象需要使用类加载器获取。

第三种使用类加载器

ServletContext context = getServletContext();
Properties properties = new Properties();
InputStream asStream = this.getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
properties.load(new InputStreamReader(asStream));
String name = properties.getProperty("name");

这里的相对路径为何如此写: …/…/file/config.properties,可能有人会有些疑惑,但只要你知道相对路径相对于谁写的就ok了。留个图供参考:
servletContext对象获取web工程下资源文件的三种方式_第1张图片

你可能感兴趣的:(javaweb,servlet)