擷取java路徑的幾種方法

來源:互聯網
上載者:User

很多情況下,我們需要在JavaBean、Servlet中獲得當前的目錄路徑,比如載入設定檔,上傳檔案到伺服器等,這是各種獲得路徑的方法的總結,備忘。

1.載入jdbc.properties

      1)ClassLoader的getResourceAsStream("XXX")

            InputStream in=XXX.class.getClassLoader().getResourceAsStream("jdbc.properties");

            getResourceAsStream()會到classes目錄下找jdbc.properties檔案,所以在工程項目中,我們一般把它放在src目錄下。

      2)Class.getResourceAsStream("/XXX")

           XXX.class.getResourceAsStream("/jdbc.properties");

      兩種方式的共同點就是:jdbc.properties都應該在classes下,也就是項目的src目錄

      不同點就是:ClassLoader.getResourceAsStream(“XXX”)中參數不以"/"開頭,而Class.getResourceAsStream("/XXX")終參數以"/"開頭

2.在Javabean中獲得路徑

  1)獲得當前類XXX.class檔案的URI目錄,不包括自己:XXX.class.getResource("")

    如:在類com.test.XXX中取得項目的根絕對路徑

    URL url=XXX.class.getResource("");

    String filename=url.getFile();

    String projectRootPath=new File(filename,"http://www.cnblogs.com/http://www.cnblogs.com/").getCanonicalPath();

    //main函數中測試

    //filename:/d:/workspace/testproject/build/calsses/com/test/

    //projectRootPath:d:/workspace/testproject

    //tomcat中測試

    //filename:/d:/tomcat/webapps/testproject/WEB-INF/calsses/com/test/

    //projectRootPath:d:/tomcat/webapps/testproject

2)獲得的是當前的classpath的絕對URI路徑:XXX.class.getResource("/")

如:在類com.test.XXX中取得項目的根絕對路徑

URL url=XXX.class.getResource("/");

String filename=url.getFile();

String projectRootPath=new File(filename,"http://www.cnblogs.com/").getCanonicalPath();

//main函數中測試

//filename:/d:/workspace/testproject/build/calsses/

//projectRootPath:d:/workspace/testproject

//tomcat中測試

//filename:/d:/tomcat/webapps/testproject/WEB-INF/calsses/

//projectRootPath:d:/tomcat/webapps/testproject

3)獲得的是當前ClassPath的絕對URI路徑:  //推薦使用

Thread.currentThread().getContextClassLoader().getResource("");

4)獲得的是當前ClassPath的絕對URI路徑:

XXX.class.getClassLoader().getResource("");

5)獲得的是當前ClassPath的絕對URI路徑:  //推薦使用

ClassLoader.getSystemResource("");

6)目前使用者目錄的相對路徑:System.getProperty("user.dir")  //不推薦使用

3.在servlet中獲得路徑

1)獲得相對路徑:

this.getServletContext().getResource("/").getPath();

//輸出:/localhost/testproject/

2)String strPath2=this.getServletContext().getRealPath("/");

//輸出:d:/tomcat/webapps/testproject/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.