java配置文件怎么用_普通的Java文件如何读取资源配置文件?

实际开发中一般不会将连接数据库的操作使用Servlet,因为我们为了分层,而是将连接数据库的操作放到dao中,这样就会用到普通的Java类来读取配置文件(.properties的文件),那么普通的Java如何来读取配置文件呢?

请看下面实例:

文件1:db.properties配置文件

userName=shxt

password=shxt

url=jdbc\:oracle\:thin\:@localhost\:1521\:ORCL

driver=oracle.jdbc.driver.OracleDriver

文件2:ch11JavaReadProperties.java 普通java文件

packagecn.com.shxt.ch10;

importjava.io.InputStream;

importjava.util.Properties;

publicclassch11JavaReadProperties {

privatestaticPropertiesdbconfig=newProperties();

privateStringurl=null;

privateStringusername=null;

privateStringpassword=null;

static{

try{

InputStreamin = ch11JavaReadProperties.class.getClassLoader()

.getResourceAsStream("db.properties");

dbconfig.load(in);

}catch(Exception e) {

e.printStackTrace();

}

}

/**

* 获取配置文件db.properties中连接数据库的参数

*/

publicvoidgetParameter() {

url=dbconfig.getProperty("url");

username=dbconfig.getProperty("userName");

password=dbconfig.getProperty("password");

System.out.println(" url:"+url+"  用户名:"+username+"   密码:"+password);

}

/**

*主测试方法

*/

publicstaticvoidmain(String[] args) {

ch11JavaReadProperties jdbc =newch11JavaReadProperties();

jdbc.getParameter();

}

}

我们只要在Servlet中实例化ch11JavaReadProperties并调用getParameter()方法就可以获取到db.properties中连接数据库的参数了。请注意:使用类装载器读取配置文件时,配置文件不宜太大,因为类装载器将配置文件装载到内存,若配置文件过大(比如1G),容易导致内存溢出的问题。

通过类装载器读取配置文件具有致命的缺点:如果服务器不重启,即使你更改了配置文件的内容,Java程序读取到的配置参数还是原来第一次配置的参数,由于程序从内存中读取配置文件的参数,因为内存中已经存在了,即使你更改了配置文件参数,内存却不会自动更新。

如果我们更改了配置文件,不用重新启动服务器就要求程序自动读取到更新后的配置文件,该怎么办呢??

请见下面程序:ch11_2JavaReadProperties .java

package cn.com.shxt.ch10;

import java.io.FileInputStream;

import java.io.InputStream;

import java.util.Properties;

public class ch11_2JavaReadProperties {

private static Properties dbconfig = new Properties();

private String url=null;

private String username=null;

private String password=null;

/**

* 获取配置文件db.properties中连接数据库的参数

*/

public void getParameter() {

try {

String path = ch11_2JavaReadProperties.class.getClassLoader()

.getResource("db.properties").getPath();

FileInputStream in=new FileInputStream(path);

dbconfig.load(in);

} catch (Exception e) {

e.printStackTrace();

}

url = dbconfig.getProperty("url");

username = dbconfig.getProperty("userName");

password = dbconfig.getProperty("password");

System.out.println(" url:" + url + "  用户名:" + username + "密码:"+ password);

}

/**

*主测试方法

*/

public static void main(String[] args) {

ch11_2JavaReadProperties jdbc = new ch11_2JavaReadProperties();

jdbc.getParameter();

}

}

本类的ch11_2JavaReadProperties.class.getClassLoader().getResource("db.properties").getPath()是把资源当做URL返回,得到资源的路径,不是再通过类装载器来读,而是通过传统的方式来读,我们通过类装载的方式来读取文件的位置,得到位置后再通过传统的读取方式来读,这样就可以避免重启服务器而可以读取到更新后的数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值