java 加载资源文件_javaWeb开发中读取资源文件方法总结

一.在servlet中读取资源文件方法

db.properties放在 src目录下,因为该目录下的资源文件发布时会发到/WEB-INF/classes目录下

如果使用如下方式去读取是不不行的

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

Properties pros = new Properties();

pros.load(in);

以上方法读取资源文件时,它会在相对JVM(也就是TOMCAT_HOME/bin/)的相对目录下去找classes/db.properties文件。

可以采用如下几种方式去读取

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

Properties props=new Properties();

props.load(in);

System.out.println(props.getProperty("url"));

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

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

Properties pros = new Properties();

pros.load(in);

二.在普通类中去读取资源文件

如果读取资源的程序不是servlet就只能用装载器去读取了

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

Properties props=new Properties();

dbconfig.load(in);

例如在userDao中读取数据库配置信息:

public class UserDao {

private static Properties dbconfig=new Properties();

static {

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

try {

dbconfig.load(in);

} catch (IOException e) {

throw new ExceptionInInitializerError(e);

}

注意:从装载器去读取的文件不能太大,因为它会以类装载的形式把文件内容装载到内存中,如果太大,导致内存占用过多,导致内存溢出。使用这种类加载的方式读取资源文件,该文件只装载一次,文件更新后不会读取到最新的数据,要想读取到最新更新的资源文件需采用下面方式。

URL url=UserDao.class.getClassLoader().getResource("db.properties");

InputStream in2=new FileInputStream(str);

Properties dbconfig=new Properties();

dbconfig.load(in2);

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值