web工程中在非servlet程序中读取配置文件

1.在web工程中,如果在servlet中读取配置文件,可以采用ServletContext,但在非servlet中,不能得到ServletContext对象,只能通过类装载器的方式读取资源文件。

 

(1)方式一:

InputStreamin = StudentDao.class.getClassLoader().getResourceAsStream("db.properties");

System.out.println(in);

这里的路径采用的是相对路径,像对的是web工程编译后的WEB-INF下面的classes目录,即在classes路径下面。           

 

 

(2)方式二:

         //用类装载方式读取,把资源当作url对待的方式很常见

                   URLurl = StudentDao.class.getClassLoader().getResource("db.properties");

                   Stringpath = url.getPath();

                   System.out.println(path);

        

2.注意用类装载器只会读取一次,如果配置文件改变了,也不会读到改变后的内容

(1)       //以下代码要注意,在线程休眠过程中,即使改动了资源文件,获取到的还是原始内容

         publicvoid test() throws IOException{

                   InputStreamin =StudentDao.class.getClassLoader().getResourceAsStream("db.properties");

                   Propertiesprop = new Properties();

                   prop.load(in);

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

                  

                   try{

                            Thread.sleep(1000*15);

                   }catch (InterruptedException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }

                  

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

                   prop= new Properties();

                   prop.load(in);

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

         }

 

 

 

 

 

 

(2)要想解决上面的问题,就是用URL的方式,先读到路径,再通过路径去读取流

         //以上问题的解决方案

         publicvoid test1() throws IOException{

                  

                   URLurl = StudentDao.class.getClassLoader().getResource("db.properties");

                   Stringpath = url.getPath();

                  

                   FileInputStreamin = new FileInputStream(path);

                   Propertiesprop = new Properties();

                   prop.load(in);

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

                  

                   try{

                            Thread.sleep(1000*15);

                   }catch (InterruptedException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }

                   in= new FileInputStream(path);

                   prop= new Properties();

                   prop.load(in);

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

         }

 

 

 

 

3. 用类装载器读取资源文件时,千万要注意,资源文件绝对不能太大,否则极易导致内存溢出

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值