1. 程式人生 > >Java獲取項目路徑及classes路徑

Java獲取項目路徑及classes路徑

servle etc getc ret ont public ssi on() real

以工程名為test為例

1.獲取項目絕對路徑一

String rootPath = request.getSession().getServletContext().getRealPath("/").replace("\\", "/");
獲取內容如下:
D:/apacheTomcat/apache-tomcat-7.0.59/webapps/test/

2.獲取web工程名

String projectName = request.getContextPath();
獲取內容如下:
/test

3.獲取classes路徑,最後的.substring(1)是為了去掉前面“/”

public static String getClassesPath(){
    String classesPath=Thread.currentThread().getContextClassLoader().getResource("").getPath().substring(1);
    return classesPath;
}

獲取內容如下:
D:/apacheTomcat/apache-tomcat-7.0.59/webapps/test/WEB-INF/classes/

4.獲取項目絕對路徑二

private static String getProjectRootPath(){
    String rootPath=Thread.currentThread().getContextClassLoader().getResource("").getPath();
    rootPath = rootPath.substring(1,rootPath.indexOf("WEB-INF"));
    return rootPath;
}

獲取內容如下:
D:/apacheTomcat/apache-tomcat-7.0.59/webapps/test/

Java獲取項目路徑及classes路徑