Java获取项目根路径及classes路径
  TEZNKK3IfmPf 2023年11月15日 32 0

以工程名为test为例(适用于web工程)

1.获取项目绝对路径一

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

//在括号内不写斜线,是为了保证在Windows和liunx中同时适用,获取tomcat里面项目的根路径(建议使用这个)
request.getSession().getServletContext().getRealPath("");

2.获取web工程名

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

3.获取classes路径

//返回项目classes目录(全路径,无线程安全问题)
public static String getClassesPath(){
	String classesPath=Thread.currentThread().getContextClassLoader().getResource("").getPath();
	// .substring(1)是为了去掉最前的"/",如果linux环境去掉"/"就不能正确获取路径
	// classesPath = classesPath.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(0,rootPath.indexOf("WEB-INF"));
	//  .substring(1)是为了去掉最前的"/",如果linux环境去掉"/"就不能正确获取路径
	rootPath = rootPath.substring(1);
	return rootPath;
}
//获取内容如下:D:/apacheTomcat/apache-tomcat-7.0.59/webapps/test/
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   19天前   43   0   0 java
  TEZNKK3IfmPf   2024年05月31日   54   0   0 java
TEZNKK3IfmPf