web中的普通Java程序如何读取资源文件

web中的普通Java程序如何读取资源文件

在Servlet中:
//servlet调用其它程序,在其它程序中如何去读取配置文件
//通过类装载器
public class ServletDemo12 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserDao user=new UserDao();
user.update();
}
}
Dao中:
//如果读取资源文件的程序不是servlet的话,
//就只能通过类转载器去读了,文件不能太大
//用传递参数(传递getcontext)方法不好,耦合性高
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");
    String str=url.getPath();——得到路径
    //file:/C:/apache-tomcat-7.0.22/webapps/day05/WEB-INF/classes/db.properties
    try {
        InputStream in2=new FileInputStream(str);
        try {
            dbconfig.load(in2);
        } catch (IOException e) {
            throw new ExceptionInInitializerError(e);
        }
    } catch (FileNotFoundException e1) {
        throw new ExceptionInInitializerError(e1);
    }       
}
public void update() {
    System.out.println(dbconfig.get("url"));
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章