假設存在一個 xxx.properties 文件
首先看該文件放置的位置
a.如果文件放在src目錄下面,這文件的路徑名就寫成:“WEB-INF/classes/資源文件名”
b.如果文件放在src目錄下面的某個包中,則文件的路徑名寫成:“WEB-INF/classes/ 包路徑/資源文件名”
c.如果文件放在webRoot文件下,則文件的路徑名寫成:“/資源文件名”
方法一:用getServletContext()方法來實現
InputStream in = this.getServletContext().getResourceAsStream("WEB-INF/classes/xxx.properties");
//獲取資源文件的輸入流
Properties pro = new Properties();
prop.load(in);//加載xxx.properties文件
prop.getProperties("屬性名");//獲取對應值
方法二:獲取絕對路徑,用傳統讀取文件的方式讀取文件
String path = this.getServletContext().getRealPath("文件路徑名");
FileInputStream in=new FileInputStream(path);
Properties pro = new Properties();
prop.load(in);//加載xxx.properties文件
prop.getProperties("屬性名");//獲取對應值
方法三:
如果讀取資源文件的程序不是servlet的話,就只能通過類加載器讀取
定義一個UserDao類在servlet doGet()方法中調用UserDao 中的meh()方法
public class UserDao(){
public void meth(){
InputStream in = UserDao.class.getClassLoader().getResourseAsStream("資源文件名"); //注意在此處的資源文件名就不需要加上“WEB-INF......”===
Properties pro = new Properties();
prop.load(in);//加載xxx.properties文件
prop.getProperties("屬性名");//獲取對應值
}
}
此方法讀取文件後,如打開網頁過後再改動資源文件,就不能讀取到更新過後的內容,對此有以下解決方法
通過類裝載的方法獲取資源文件的絕對位置,在用傳統的文件讀取方法讀取文件,這樣就能獲取到更新過後的文件
String path = UserDao.class.getClassLoader().getSource("資源文件名").getPath();
FileInputStream in=new FileInputStream(path);
Properties pro = new Properties();
prop.load(in);//加載xxx.properties文件
prop.getProperties("屬性名");//獲取對應值
getSource("資源名")得到該文件的絕對路徑,返回時一個URL類型