properties文件读取

来源:互联网 发布:java基础编程题 编辑:程序博客网 时间:2024/06/07 11:56

一、在servlet中的读取方式(基于properties文件放在src下)

方法1.

大众方法

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

Properties props = new Properties();

props.load(in);

String url = props.getProperty("url");

String username = props.getProperty("username");

String password = props.getProperty("password");

System.out.println(url);

System.out.println(username);

System.out.println(password);

方法2.

使用getServletContext()调用getRealPath()方法得到文件的位置,然后再用传统的方式读取内容。

可以拿到资源名称(下载应用的时候用这种方式)

 

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

String fileName = path.substring(path.lastIndexOf("\\")+1);

FileInputStream in = new FileInputStream(path);//传统方法

Properties props = new Properties();

props.load(in);

String url = props.getProperty("url");

 

System.out.println(fileName);

System.out.println(url);

输出结果是:

db.properties

...

方法3.

servlet中用传统的方式通过相对路径找到文件的位置读取内容。

这种方法必须在E:\apache-tomcat-7.0.29\bin目录下新建一个/classes/db.properties文件,为什么呢?

首先我们要知道相对路径是相对于谁?是相对于E:\apache-tomcat-7.0.29\bin因为Tomcat的启动程序在这个目录下,所以在这个路径下建立出properties,就可以访问到了。

FileInputStream in = new FileInputStream("classes/db.properties");

Properties props = new Properties();

props.load(in);

String url = props.getProperty("url");

String username = props.getProperty("username");

String password = props.getProperty("password");

System.out.println(url);

System.out.println(username);

System.out.println(password);

二、在普通java代码中的读取方式

     只能通过类装载器来读取配置文件

方法1.

properties文件在包下时,读取方式如下:

InputStream in = UserDao.class.getClassLoader().getResourceAsStream("cn/itcast/dao/db.properties");

InputStream in = UserDao.class.getResourceAsStream("db.properties");

Properties props = new Properties();

props.load(in);

String url = props.getProperty("url");

System.out.println(url);

方法2.

properties文件在src下时,读取方式如下: 

InputStream in = UserDao.class.getClassLoader().getResourceAsStream("db.properties");

Properties props = new Properties();

props.load(in);

String url = props.getProperty("url");

System.out.println(url);

以上读取方式存在一个问题,就是properties文件和字节码文件同时加载到内存,那么字节码只加载一次,properties文件也就只加载一次,当properties文件更新后,不重启服务器的情况下,我们读取到的不是更新后的properties文件,而是内存中的文件,那么我们怎么读取到更新后的文件呢?见方法3

方法3.

使用类装载的方式得到文件的位置,然后再用传统的方式读取内容

String path = UserDao.class.getClassLoader().getResource("db.properties").getPath();

FileInputStream in = new FileInputStream(path);

Properties props = new Properties();

props.load(in);

String url = props.getProperty("url");

System.out.println(url);

这相当与把properties文件的路径和字节码同时加载到了内存,虚拟机会根据路径找到properties文件,然后提取内容,这样就可以读取到更新后的properties文件内容。

注:读取其他文件的方式大同小异,这里只是以.properties文件为例。

原创粉丝点击