積少成多

          垃圾堆

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            29 Posts :: 1 Stories :: 5 Comments :: 0 Trackbacks

          2013年10月18日 #

          如果是Servlet , Action , Controller, 或則Filter , Listener , 攔截器等相關類時, 我們只需要獲得ServletContext, 然后通過ServletContext.getRealPath("/")來獲取當前應用在服務器上的物理地址

          如果在類中取不到ServletContext時, 有兩種方式可以做到

          1) 利用Java的類加載機制 調用 XXX.class.getClassLoader().getResource(""); 方法來獲取到ClassPath , 然后處理獲得WebRoot目錄,這種方式只能是該class在WebRoot/WEB-INF/classes下才能生效, 如果該class被打包到一個jar文件中, 則該方法失效。這時就應該用下面一種方式

          2) spring框架的思路, 在WEB-INF/web.xml中 , 創建一個webAppRootKey的param, 指定一個值(默認為webapp.root)作為鍵值, 然后通過Listener , 或者Filter , 或者Servlet 執行String webAppRootKey = getServletContext().getRealPath("/"); 并將webAppRootKey對應的webapp.root 分別作為Key , Value寫到System Properties系統屬性中。之后在程序中通過System.getProperty("webapp.root")來獲得WebRoot的物理路徑


          下面是一些得到classpath和當前類的絕對路徑的一些方法。你可使用其中的一些方法來得到你需要的資源的絕對路徑:

            1.DebitNoteAction.class.getResource("")

            得到的是當前類FileTest.class文件的URI目錄。不包括自己!

            如:file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/atacarnet/src/com/evi/modules/atacarnet/action/

            2.DebitNoteAction.class.getResource("/")

            得到的是當前的classpath的絕對URI路徑。

            如:file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/

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

            得到的也是當前ClassPath的絕對URI路徑

            如:file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/

            4.DebitNoteAction.class.getClassLoader().getResource("") 或ClassLoader.getSystemResource("")

            得到的也是當前ClassPath的絕對URI路徑。

            如:file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/

            5.取得服務器相對路徑

            System.getProperty("user.dir")

            例如:E:\apache-tomcat-5.5.16\apache-tomcat-5.5.16\bin

            我推薦使用Thread.currentThread().getContextClassLoader().getResource("")來得到當前的classpath的絕對路徑的URI表示法

            6.取得項目中的絕對路徑

            一般用request.getRealPath("/")或request.getRealPath("/config/")

            但現在不提倡使用request.getRealPath("/")了,大家可試用ServletContext.getRealPath("/")方法得到Web應用程序的根目錄的絕對路徑

            要取得src的文件非常容易,因為src是默認的相對目錄,比如你說要取得src下com目錄的test.java文件,你只需要這樣就夠了

            File f = new File(com/test.java);

            但如果我要取得不在src目錄或者WebRoot目錄下的文件呢,而是要從src或者WebRoot同級的目錄中取呢,比如說doc吧

            我的硬方法是這樣實現的:

            String path = this.getServletContext().getRealPath("/");

            Properties p = new Properties();

            p.load(new FileInputStream(new File(path.substring(0,(path.lastIndexOf("\\WebRoot") + 1)) + "doc/db.properties")));

            System.out.println(p.getProperty("driverName"));

          posted @ 2013-10-18 21:29 思無 閱讀(11535) | 評論 (1)編輯 收藏

          主站蜘蛛池模板: 禄丰县| 张家港市| 珠海市| 竹溪县| 瑞安市| 甘南县| 上杭县| 尖扎县| 长岛县| 富平县| 和林格尔县| 宜章县| 德兴市| 高州市| 东光县| 金华市| 南通市| 邵武市| 枣阳市| 久治县| 怀集县| 石台县| 菏泽市| 微山县| 平邑县| 鄢陵县| 阜平县| 安康市| 大邑县| 新郑市| 托克逊县| 尖扎县| 葫芦岛市| 正宁县| 阜阳市| 皮山县| 阜宁县| 津市市| 商南县| 高雄县| 顺平县|