Servlet獲取資源文件的方式總結
最近在學習JavaWeb,同時也因爲ServletContext獲取資源文件的方式而苦惱,
一個最直截了當的問題就是:爲什麼方式有這麼多?太容易弄混了!
確實,看了視頻教程之後,首先感覺到在Web工程中想要獲取資源文件信息和普通的Java工程是不一樣的,因爲這是在Web工程而不是Java工程,即使我們的文件放在src下,但是,真正的相對路徑不是在src下,真正的絕對路徑也不是在Java工作空間中。由於我們的Web工程是寄託在Tomcat中來運行,所以運行的路徑是在Tomcat項目目錄下的classes中,故這也是本人爲什麼要總結的原因!以下爲重點:
-
ServletContext - 普通方式讀取工程文件
- 首先,如果我們在EclipseWeb項目中src目錄下,新建一個properties配置文件,並寫上信息,若要讀取,最原始方法是的使用Properties加載FileInputStream(PS:這也是我們學JavaSE所通常使用的方法)但是這種方法有以下注意點及侷限性:
- 實例化InputStream的代碼過於囉嗦,文件路徑太長(不是相對路徑)
- 以下爲該方法的代碼:
Properties properties = new Properties(); InputStream is = new FileInputStream("D:/apache-tomcat-7.0.77/wtpwebapps/Servlet/WEB-INF/classes/peizhi.properties"); properties.load(is); String name = properties.getProperty("name"); //這裏以獲取name爲例 System.out.println("name="+name);
-
ServletContext - 獲取資源文件(一)
- 該方法比上面的方法方便,仍然是Properties加載InputStream來實現,還加入了ServletContext對象來獲取InputStream,就不用像上面那樣填寫複雜的路徑了,這種方法有以下注意點:
- 使用到了ServletContext的getRealPath(“WEB-INF/classes/peizhi.properties”);
- 該方法指向的目錄爲:項目工程名的目錄下
- 所以路徑爲:WEB-INF/classes/peizhi.properties
- 以下爲該方法的代碼:
Properties properties = new Properties(); ServletContext sc = getServletContext(); InputStream is = null; String path = sc.getRealPath("WEB-INF/classes/peizhi.properties"); //System.out.println("path="+path); is = new FileInputStream(path); properties.load(is); String name = properties.getProperty("name"); System.out.println("name="+name);
-
ServletContext - 獲取資源文件(二)
- 該方法比第一種方法方便(和第二種類似),這種方法有以下注意點:
- 使用到了ServletContext的getResourceAsStream方法
- getResourceAsStream方法指向的目錄在Tomcat的根目錄工程下,即wtpwebapps\項目工程名
- 所以路徑爲:WEB-INF/classes/peizhi.properties
- 以下爲該方法的代碼:
ServletContext sc = getServletContext(); Properties properties = new Properties(); InputStream is = null; is = sc.getResourceAsStream("WEB-INF/classes/peizhi.properties"); properties.load(is); String name = properties.getProperty("name"); System.out.println("name="+name);
-
ServletContext - 使用ClassLoader獲取資源文件
- 該方法與上面的兩種方法類似,也是使用properties與InputStream,只不過是使用ClassLoader來完成
- this.getClass().getResourceAsStream("…/name.properties");指向:classes\Servlet
- this.gerClass().getClassLoader().getResourceAsStream(“name
.properties”);指向:classes - 以下爲該方法的代碼:
Properties properties = new Properties(); InputStream is = null; is = this.getClass().getClassLoader().getResourceAsStream("peizhi.properties"); properties.load(is); String name = properties.getProperty("name"); System.out.println("name="+name);
最後:本人爲大二菜雞一枚,希望對一些和我一樣學習Web有疑惑的同學有所幫助。PS:第一次寫博客,竟然寫了近兩個小時!