在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();
}
}