1. ServletContext

1. 调用getResourcesAsStream方法获取输入流, 相对于webroot, 不用加/
2. 读取任何类型的文件
3. *只能在web环境下使用

InputStream in = this.getServletContext().getResourceAsStream("WEB-INF/classes/config/db.properties");

2. 类加载器

1. 相对于类路径, 可以获取类路径下及其子包路径下的资源文件
2. 可以用在非web环境下
3. 读取任何类型的文件

InputStream in = ReadFileDemo2.class.getResourceAsStream("/config/db.properties");

3. 流

1. 通过ServletContext的getRealPath方法获取文件真实路径, 然后操作文件流, 相对于webroot. 不用加/

String realPath = this.getServletContext().getRealPath("WEB-INF/classes/config/db.properties");

4. ResourceBundle

新建4个资源文件

1 my_en_US.properties:cancelKey=cancel
2 my_zh_CN.properties:cancelKey=\u53D6\u6D88(取消)
3 my_zh.properties:cancelKey=\u53D6\u6D88zh(取消zh)
4 my.properties:cancelKey=\u53D6\u6D88default(取消default)

使用ResourceBundle读取资源文件

1 ResourceBundle bundle = ResourceBundle.getBundle("my", new Locale("zh", "CN"));
2 String cancel = bundle.getString("cancelKey");
3 System.out.println(cancel);

1. 可以用在非web环境下
2. 只能读取类路径中的properties文件

 

备注: ServletContext和流两种方法的区别在于获取流的方式不一样

分类:

技术点:

相关文章: