天天看點

擷取路徑

擷取路徑的方法:

1、在java類中擷取路徑(com.zhanggm.Test.java)

// 方式1,通過classZLoader擷取路徑,參數必須是""。
this.getClass().getClassLoader().getResource("");
// 結果為:“file:/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/”,類型是java.net.URL。
this.getClass().getClassLoader().getResource("").getPath();
// 結果為:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/”,類型是String。

// 方式2,直接擷取,參數可以随意指定,""擷取目前類所在的路徑、"/"擷取根路徑(即.../classes/)、"/xx/xx"、"/xx/xx/"等
this.getClass().getResource("").getPath();
// 結果為:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/com/zhanggm/”
this.getClass().getResource("/").getPath();
// 結果為:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/”
this.getClass().getResource("/com").getPath();
// 結果為:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/com”
this.getClass().getResource("/com/").getPath();
// 結果為:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/com/”
this.getClass().getResource("com").getPath();
// 結果為:“null”
this.getClass().getResource("com/").getPath();
// 結果為:“null”
this.getClass().getResource("/zhanggm").getPath();
// 結果為:“null”      

2、通過 request 擷取路徑

String absolutePath= request.getRealPath("/");
// 結果為:“/D:/workspace/strutsTest/WebRoot/”,即擷取是本地的絕對路徑,WEB-INF所在的目錄。這個路徑可以用來存放檔案。

String contextPath  = request.getContextPath();
// 結果為:“1、有項目名:"/xxPojectName",2、沒有項目名:""”      

3、在 struts2 中擷取路徑

String absolutePath = org.apache.struts2.ServletActionContext.getServletContext().getRealPath("/upload/");
// 結果為:“/D:/workspace/strutsTest/WebRoot/upload/”,即擷取是本地的絕對路徑。這個路徑可以用來存放檔案。      
/**
     * 擷取應用的路徑
     *
     * @return 應用的路徑
     */
    protected String getAppPath() {
        org.springframework.web.context.WebApplicationContext webApplicationContext = org.springframework.web.context.ContextLoader.getCurrentWebApplicationContext();
        javax.servlet.ServletContext servletContext = webApplicationContext.getServletContext();
        return servletContext.getContextPath();
    }