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

javaweb工程 配置文件读取

2017-06-27 10:38 281 查看
test.properties文件中如下:
username=root
pwd=123


一、类路径(src)下配置文件读取

这里给出两种方式:

1.类加载器
要求:文件必须是类路径下。文件后缀可以是.xml也可以是.properties


//1.获取类加载器
ClassLoader cl = 当前类名.class.getClassLoader();
//2.读取文件,只能读取类路径下的
InputStream in = cl.getResourceAsStream("test.properties");//参数写法按照类路径
来写(此处为类路径同级文件) 举例com/java/包名/test.properties
//3.创建一个Properties对象
Properties props = new Properties();
//4.加载流对象
props.load(in);
//5.获取值
String username = props.getProperty("username");//用户名
String pwd = props.getProperty("pwd");//密码


2.通过ResourceBundle(java.util包下)对象,根据资源文件获取bundle对象
要求:1.只能用于读取,不能写入
2.只能读取资源文件后缀为 .properties的文件
3.文件在类路径下


//如果有包名写法为:com.file.source.test(千万不要把资源文件后缀添加进来)
ResourceBundle bundle = ResourceBundle.getBundle("test");
String username = bundle.getString("username");
String pwd = bundle.getString("pwd");


注意:为什么没给出用InputStream流直接读取文件?因为在当前环境(比如windows下)是没问题的,但是
一旦项目部署到linux系统中,文件位置不一定找得到。


二、WEB-INF下的配置文件

可以直接通过InputStream流对象直接读取,但需要获取文件的真实路径!
String realPath = this.getServletContext.getRealPath("/WEB-INF/test.properties");
以下就简单了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息