properties文件读取

布满荆棘的人生 2021-12-23 18:17 631阅读 0赞

一、在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. 只能通过类装载器来读取配置文件

方法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文件为例。

发表评论

表情:
评论列表 (有 0 条评论,631人围观)

还没有评论,来说两句吧...

相关阅读

    相关 读取Properties配置文件

    通过读取properties文件获取配置项的值在开发中是很常用的,这种方式降低了变量和代码间的耦合,使得非开发人员也可以很容易的对系统的一些配置进行修改,比如配置数据库连接参数