javaWeb开发中读取资源文件方法总结
一.在servlet中读取资源文件方法
db.properties放在 src目录下,因为该目录下的资源文件发布时会发到/WEB-INF/classes目录下
如果使用如下方式去读取是不不行的
FileInputStream in = new FileInputStream("/classes/db.properties");
Properties pros = new Properties();
pros.load(in);
以上方法读取资源文件时,它会在相对JVM(也就是TOMCAT_HOME/bin/)的相对目录下去找classes/db.properties文件。
可以采用如下几种方式去读取
1. InputStreamin=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties props=new Properties();
props.load(in);
System.out.println(props.getProperty("url"));
2. String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
FileInputStream in = new FileInputStream("/classes/db.properties");
Properties pros = new Properties();
pros.load(in);
二.在普通类中去读取资源文件
如果读取资源的程序不是servlet就只能用装载器去读取了
InputStream in=UserDao.class.getClassLoader().getResourceAsStream("db.properties");
Properties props=new Properties();
dbconfig.load(in);
例如在userDao中读取数据库配置信息:
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
InputStream in2=new FileInputStream(str);
Properties dbconfig=new Properties();
dbconfig.load(in2);