問題描述:
在顯示Web應用目錄下圖片1.png時調用new FileInputStream(this.getServletContext().getRealPath(1.png))時拋出空指針異常:
嚴重: Servlet.service() for servlet [downloadServlet] in context with path [/Servlet] threw exception
java.lang.NullPointerException
解決:經反復確定代碼輸入及路徑正常后,查找到此解決方案servletContext.getRealPath(),在此闡述一下個人理解:
context.getRealPath("/")在不同的服務器上所獲得的實現是不一樣的,對一個打包的應用來說,是沒有RealPath的概念的,調用getRealPath只會簡單地返回null。其實,也很好理解,一個文件被打包入了.war文件,就不存在目錄結構了(雖然包中仍然存在目錄結構,但這不等同於文件系統中的目錄結構)。所以,對war包中的資源是無法得到RealPath的。這樣也就無從通過文件IO進行讀取了。
建議:
(1)使用ServletContext.getResourceAsStream("/WEB-INF/config/aa.config")方法替代
例如:InputStream in = this.getServletContext().getResourceAsStream("/1.jpg");
(2)調用this.getClass().getClassLoader().getResource("/").getPath(); 獲取到classes目錄的全路徑,在得到classes目錄的全路徑后再根據字符串的截取與拼裝達到你的要求即可。
(2)調用this.getClass().getClassLoader().getResource("/").getPath(); 獲取到classes目錄的全路徑,在得到classes目錄的全路徑后再根據字符串的截取與拼裝達到你的要求即可。
例如:InputStream in =new FileInputStream(this.getClass().getClassLoader().getResource("../../1.jpg").getPath());