1.在web工程中,如果在servlet中读取配置文件,可以采用ServletContext,但在非servlet中,不能得到ServletContext对象,只能通过类装载器的方式读取资源文件。
(1)方式一:
InputStreamin = StudentDao.class.getClassLoader().getResourceAsStream("db.properties");
System.out.println(in);
这里的路径采用的是相对路径,像对的是web工程编译后的WEB-INF下面的classes目录,即在classes路径下面。
(2)方式二:
//用类装载方式读取,把资源当作url对待的方式很常见
URLurl = StudentDao.class.getClassLoader().getResource("db.properties");
Stringpath = url.getPath();
System.out.println(path);
2.注意用类装载器只会读取一次,如果配置文件改变了,也不会读到改变后的内容
(1) //以下代码要注意,在线程休眠过程中,即使改动了资源文件,获取到的还是原始内容
publicvoid test() throws IOException{
InputStreamin =StudentDao.class.getClassLoader().getResourceAsStream("db.properties");
Propertiesprop = new Properties();
prop.load(in);
System.out.println(prop.getProperty("url"));
try{
Thread.sleep(1000*15);
}catch (InterruptedException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
in=StudentDao.class.getClassLoader().getResourceAsStream("db.properties");
prop= new Properties();
prop.load(in);
System.out.println(prop.getProperty("url"));
}
(2)要想解决上面的问题,就是用URL的方式,先读到路径,再通过路径去读取流
//以上问题的解决方案
publicvoid test1() throws IOException{
URLurl = StudentDao.class.getClassLoader().getResource("db.properties");
Stringpath = url.getPath();
FileInputStreamin = new FileInputStream(path);
Propertiesprop = new Properties();
prop.load(in);
System.out.println(prop.getProperty("url"));
try{
Thread.sleep(1000*15);
}catch (InterruptedException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
in= new FileInputStream(path);
prop= new Properties();
prop.load(in);
System.out.println(prop.getProperty("url"));
}
3. 用类装载器读取资源文件时,千万要注意,资源文件绝对不能太大,否则极易导致内存溢出