javaWeb專案下獲取當前類的絕對路徑
阿新 • • 發佈:2019-02-04
在開發中我們經常會對檔案進行操作,所以也就經常涉及到檔案路徑問題。那麼在JavaWeb專案中如何獲取當前專案或Java類的路徑呢?
如下程式碼是一個簡單的Servlet 類:
由上程式碼可以得出有兩種方法獲取當前專案的路徑。一是this.getServletContext().getRealPath("");即通過Servlet上下文物件獲取路徑,該路徑指向當前Servlet容器所在位置,也就是當前專案路徑;二是通過類載入器獲取當前類的路徑,在這裡特別提醒:所有類的路徑都指向 伺服器路徑/專案名稱/WEB-INF/classes/ ,因為專案釋出後所有的.class 檔案都放在這個目錄下。public class First extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 情況1 String realPath = this.getServletContext().getRealPath(""); System.out.println(realPath); // E:\Server\tomcat-6.0.30\webapps\Day003 // 情況2 ClassLoader classLoader = this.getClass().getClassLoader(); String path = classLoader.getResource("").getPath(); System.out.println(path); // /E:/Server/tomcat-6.0.30/webapps/Day003/WEB-INF/classes/ } }
既然得到了以上資訊,那麼我們如何來讀取專案下的一個檔案呢?檔案所在位置如下:
操作程式碼如下:
由上可知,不能使用InputStream is = new FileInputStream("1.jpg"); 因為web專案釋出到伺服器後文件目錄有所改變。所以只能使用上面的情況2,和情況3進行本專案下的檔案操作。public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 情況1 // InputStream is = new FileInputStream("1.jpg"); // 報錯, java.io.FileNotFoundException: 1.jpg (系統找不到指定的檔案。) File file = new File("1.jpg"); System.out.println(file.getAbsolutePath()); // E:\Server\tomcat-6.0.30\bin\1.jpg // 情況2 String realPath = this.getServletContext().getRealPath("1.jpg"); InputStream is2 = new FileInputStream(realPath); // 情況3 ClassLoader classLoader = this.getClass().getClassLoader(); String path = classLoader.getResource("../../1.jpg").getPath(); InputStream is3 = new FileInputStream(realPath); }