1. 程式人生 > >利用ServletContext物件讀取資原始檔(比如properties檔案)

利用ServletContext物件讀取資原始檔(比如properties檔案)

讀取資原始檔要根據資原始檔所在的位置來決定,一般分為以下兩種情況:

 

4.1:檔案在WebRoot資料夾下,即Web應用的根目錄。這時候我們可以使用ServletContext來讀取該資原始檔。

假設我們Web根目錄下有一個配置資料庫資訊的dbinfo.properties檔案,裡面配置了name和password屬性,這時候可以通過ServletContext去讀取這個檔案:

// 這種方法的預設讀取路徑就是Web應用的根目錄
InputStream stream = this.getServletContext().getResourceAsStream("dbinfo.properties");
// 建立屬性物件
Properties properties = new Properties();
properties.load(stream);
String name = properties.getProperty("name");
String password = properties.getProperty("password");
out.println("name="+name+";password="+password);

4.2:如果這個檔案放在了src目錄下,這時就不能用ServletContext來讀取了,必須要使用類載入器去讀取。

// 類載入器的預設讀取路徑是src根目錄
InputStream stream = MyServlet.class.getClassLoader().getResourceAsStream("dbinfo.properties")如果這個檔案此時還沒有直接在src目錄下,而是在src目錄下的某個包下,比如在com.gavin包下,此時類載入器要加上包的路徑,如下:

InputStream stream = MyServlet.class.getClassLoader().getResourceAsStream("com/gavin/dbinfo.properties")

補充一點,ServletContext只有在讀取的檔案在web應用的根目錄下時,才能獲取檔案的全路徑。比如我們在WebRoot資料夾下有一個images資料夾,images資料夾下有一個Servlet.jpg圖片,為了得到這個圖片的全路徑,如下:

// 如何讀取到一個檔案的全路徑,這裡會得到在Tomcat的全路徑
String path = this.getServletContext().getRealPath("/images/Servlet.jpg");

 

轉載自W3CSCHOOLhttps://www.w3cschool.cn/servlet/servlet-3ceg2p0t.html