在JSP中读取配置文件分两种情况,第一种是从在servlet中读,第二种是在普通类(比如dao中读取数据库配置)中读。
第一种情况的读取方法:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//先得到一个java.util.Properties
//Properties p=method1();//第一种方法
Properties p=method2();//第二种方法,可以得到文件名
//从p中取出数据
//方法一
Enumeration e=p.propertyNames();
while(e.hasMoreElements()){
String key=(String) e.nextElement();
response.getWriter().print(key+":"+p.getProperty(key)+"<br/>");
}
response.getWriter().write("------------------------<br/>");
//方法二
Set<Entry<Object, Object>> s=p.entrySet();
for(Entry en:s){
response.getWriter().write(en.getKey()+":"+en.getValue()+"<br/>");
}
}
//第一种方法
public Properties method1() throws IOException {
/**
* 1.通过ServletContext对象得到一个文件的流,注意文件路径的写法,这里是直接话应该程序的WEB-INF目录下的,
* 如果是放在项目的src下,则这里的路径应该是:/WEB-INF/classes/db.properties,不过一般不会这么放
*/
InputStream instm=this.getServletContext().getResourceAsStream("/WEB-INF/db.properties");
//2.创建一个java.util.Properties类(此类实现了map接口),从instm输入流中读取文件的属性列表(键值对形式)
Properties p=new Properties();
p.load(instm);
return p;
}
//第二种方法,可以得到文件名
public Properties method2() throws IOException{
String path=this.getServletContext().getRealPath("/WEB-INF/db.properties");
FileInputStream fis=new FileInputStream(path);
Properties p=new Properties();
p.load(fis);
return p;
}
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
第二种情况的读取方法:
public class UserDao {
//在普通类下读取配置文件
public void readCfg(){
//1,通过类装载器得到这个文件的url
/**
* 注意:a.这里如果用.getResourceAsStream()直接得到一个流的话,那么在改动文件时,只有重新发布,
* 才能得到最新的数据,因为这个流是能过类装载器得到的,而类只有在发布时只装载一次的,
* 这也是为什么当类改动时,只有重新发布后,才有效果的原因,
* b.并且读取的文件不能太大,
* c.这里要写相对路径,
*/
URL url=UserDao.class.getClassLoader().getResource("../db.properties");//注意
//2.通过url得到文件的路径
String path=url.getPath();
try {
//3,得到一个输入流
FileInputStream fis=new FileInputStream(path);
//InputStream fis=this.getClass().getClassLoader().getResourceAsStream("../db.properties");//这种不行
//4.从输入流中读取文件的属性列表
Properties p=new Properties();
p.load(fis);
//5.输出,使用数据
System.out.println(p.getProperty("url"));
} catch (FileNotFoundException e) {
throw new ExceptionInInitializerError();//如果这个异常是致命的(比如数据库连不了),可以抛出这个错误
} catch (IOException e) {
e.printStackTrace();
}
}