读取web中的资源配置文件

一.软件开发过程中常有的两种配置文件是:

       1. .xml配置文件

        2. .properties配置文件

        当要用的数据间没有关系是用到.properties文件。

二.在servlet中一般使用ServletContext读取.properites配置文件。一般代码格式为:

      InputStream in=this.getServletContext().getResourceAsStream("对应web映射到服务器下得目录");

      Properties prop=new Properties();

      rops.load(in);

      props.getProperty("");//对应properties文件中等号(“=”)左面的数据

三.如配置文件为:

      url=jdbc:mysql://localhost:3306/test
      username=root
      password=root

     读取方式:

       InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");//目录为服务器下对应的目录,在本地磁盘映射到服务器下得目录,               此      处是在本地src目录下若再cn.itcast包下则为/WEB-INF/classes/cn/itcast/db.properties,若在webroot下则直接为/db.properties
        Properties props=new Properties();//map
        props.load(in);
        
        String url=props.getProperty("url");
        String username=props.getProperty("username");
        String password=props.getProperty("password");

注:

读取资源文件需要注意的问题:下面代码不可行,最好采用servletContext去读
    private void test4() throws IOException {
        FileInputStream in =new FileInputStream("src/db.properties");//改成classes目录也不行,采用相对路径,相对类加载器的目录(服务器启动目录)
        Properties props=new Properties();
        props.load(in);
     可以通过servletContext的getRealPath得到资源的绝对路径后,再通过传统流读取资源文件,可以得到文件的名称
    private void test5() throws IOException {
        String path=this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
        FileInputStream in=new FileInputStream(path);
        Properties props=new Properties();
        props.load(in);   

四.得到配置文件的文件名

        String path=this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");//得到真实路径名
        String filename=path.substring(path.lastIndexOf("\\")+1);//注意加1
        System.out.println("当前读取到得资源名称是:"+filename);
        FileInputStream in=new FileInputStream(path);
        Properties props=new Properties();
        props.load(in);    

五.不是servlet的java程序读取web配置文件

      虽然可以使用参数传递ServletContext,但不使用,外部侵入了数据库层,不符合软件设计思想。只能通过类装载器去读了,类装载器不仅可以装载类,也可以装载配置文件。

         Properties dbconfig=new Properties();
        InputStream in=UserDao.class.getClassLoader().getResourceAsStream("db.properties");
        dbconfig.load(in);

      虽然可以读取资源文件的数据,但是无法获取更新后的数据。通过类装载器的方式得到资源文件的位置,再通过传统方式读取资源文件的数据,这样可以读取到更新后的数据:

      String path=UserDao.class.getClassLoader().getResource("db.properties").getPath();
        
        FileInputStream in=new FileInputStream(path);
        Properties dbconfig=new Properties();
        dbconfig.load(in);

       注意:servletcontext读取的配置文件不能太大

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值