以eclipse中的java web項目為例,properties文件作為資源文件
有如下結構的項目,在WebContent、WEB-INF及src下分別有db1.properties,db2.properties,db3.properties三個文件。

在Servlet中使用ServletContent獲取資源文件時,常用的方法有:
1.getResourceAsStream(path)
path即資源文件的路徑寫法:
(1)如果資源文件放在src下的某個包下面:/WEB-INF/classes/包名/文件名
例獲取如上圖src下的servlet.study包下的db3.properties文件,寫法:
InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/servlet/study/db3.properties");
(2)如果資源文件放在WebContent即Web根目錄下面:/文件名(這里以eclipse中的web項目為例,和WebRoot是一個道理)
例獲取如上圖WebContent下的db1.properties文件,寫法:
InputStream in=this.getServletContext().getResourceAsStream("/db1.properties");
(3)如果資源文件放在WEB-INF下面:/WEB-INF/文件名
例獲取如上圖WEB-INF下的db2.properties文件,寫法:
InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/db2.properties");
2.getRealPath(path)
此方法的path是文件的絕對路徑
例獲取如上圖src下的servlet.study包下的db3.properties文件,寫法:
String path=this.getServletContext().getRealPath("/WEB-INF/classes/servlet/study/db3.properties");
