java程序读取资源文件

来源:互联网 发布:侠义英雄坐骑进阶数据 编辑:程序博客网 时间:2024/06/05 04:41

在servlet中通过servletContext读取资源文件,那么在非servlet中可以通过类装载器读取资源文件。
在src目录下编写数据库资源文件:db.properties

url=jdbc:mysql://localhost:3306/testusername=rootpassword=root

ServletDemo12调用dao操作数据库:

package cn.sun;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.sun.dao.UserDao;public class ServletDemo12 extends HttpServlet {        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {                       UserDao dao=new UserDao();  //调用dao去操作数据库        dao.update();           }   }

UserDao读取资源文件:

package cn.sun.dao;import java.io.IOException;import java.io.InputStream;import java.util.Properties;//servlet调用其他程序,在其他程序中如何读取资源文件(通过类装载器) 注:这个资源文件不能太大//如果读取资源文件的程序不是servlet的话,就只能通过类装载器去读public class UserDao {    private static Properties dbconfig=new Properties(); //封装数据库配置信息    static{  //静态代码块        try{            //通过类装载器读取配置文件,操作配置文件里的数据库            InputStream in=UserDao.class.getClassLoader().getResourceAsStream("db.properties");  //得到这个类的类装载器,装载db.properties,返回一个流            dbconfig.load(in);  //把流的数据装载到dbconfig中                     }catch(Exception e){            throw new ExceptionInInitializerError(e);  //抛出异常给上一级        }    }    public void update() throws IOException{        System.out.println(dbconfig.getProperty("url"));            }}

运行http://localhost:8080/day05/ServletDemo12,控制台输出:
这里写图片描述


但是

:以上代码虽然可以读取资源文件的数据,但是无法获取更新后的数据,更改UserDao.java:

package cn.sun.dao;import java.io.FileInputStream;import java.io.IOException;import java.util.Properties;//servlet调用其他程序,在其他程序中如何读取资源文件(通过类装载器) 注:这个资源文件不能太大//如果读取资源文件的程序不是servlet的话,就只能通过类装载器去读public class UserDao {    public void update() throws IOException{                //通过类装载的方式得到资源文件的位置,再通过传统方式读取资源文件的数据,这样可以读取到更新后资源文件里的数据        String path=UserDao.class.getClassLoader().getResource("db.properties").getPath(); //通过类装载器.得到资源的路径        FileInputStream in=new FileInputStream(path); //通过流读取        Properties dbconfig=new Properties();        dbconfig.load(in);        System.out.println(dbconfig.getProperty("url"));    }}

运行http://localhost:8080/day05/ServletDemo12,控制台输出更改后的properties资源文件内容:
这里写图片描述

0 0