WEB应用中资源文件的读取和常用配置文件

来源:互联网 发布:淘宝凑单什么意思 编辑:程序博客网 时间:2024/05/17 08:17

               WEB应用中资源文件的读取和常用配置文件

web应用中如果读取资源文件的程序不是Servlet就只能通过类装载器去读,有两种方式:

1.通过InputStream流进行读取

   首先调用该类的类装载器,然后调用getResourceAsStream()获得InputStream流对象在创建Properties对象newProperties()在调用该类的Coad()方法。例如:

InputStream  in=UserDao.class.getClassLoader().getResourceAsStream();

Properties  proper=new  Properties();

proper.load(in);

proper.getProperty();

如果在该类中有多处需要加载类加载器资源,可以将加载该资源的代码声明在静态代码快中,如果在该代码块中需要抛出编译时异常,可以抛出错误。

2.通过普通流来读取

   首先获得该类装载器,在获得该资源的URL如(UserDao.class.getClassLocaer()),然后获得该资源的路径getPath(),最后在通过FileInputStream流来读取。

String path=UserDao.class.getClassLoader().getResource(path).getPath();

FileInputStream in=new FileInputStream(path);

Properties proper=new Properties();

proper.load(in);

proper.getProperty(“”);

WEB应用中经常使用的配置文件有:xml文件和properties文件。如果配置文件的数据无关系就用properties文件,有关系就用xml文件。在web中使用ServletContext读取web资源文件!

1.首先获取ServletContext在获取InputStream;

如:InputStream  in=this.getServletContext().getResourceAsStream();

Properties pro=new Properties();

Pro.load(in);

2.其次获取Servletcontext在获取该资源文件的绝对路径

String path =this.getServletContext().getRealPath(path);

FileInputStream in=new FileInputStream(path);

Properties  pro=new Properties();

Pro.load(in);

3.不能使用以下方式读取资源文件

 FileInputStream  in=new FileInputStream(path);

该参数path是相对于JAVA虚拟机寻找资源即在tomcat目录中寻找次时文件路径在tomcat中不存在!

Properties pro=new Properties();

Pro.load(in);

Servlet配置文件中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数,当servlet配置初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletCongfig对象中,并在调用servletinit()方法时,将servletCongfig对象传递给servlet,程序员通过servletConfig对象来得到Servlet的初始化参数信息ServletConfig对象调用getInitParamter(“”)来获得配置信息!!

原创粉丝点击