java获取路径几种途径

来源:互联网 发布:php 明天0点的时间戳 编辑:程序博客网 时间:2024/05/16 12:23
1.可以在servlet的init方法里
String path = getServletContext().getRealPath("/");
这将获取web项目的全路径
例如 :E:\eclipseM9\workspace\tree\
tree是我web项目的根目录
 
2.你也可以随时在任意的class里调用
this.getClass().getClassLoader().getResource("/").getPath();
这将获取 到classes目录的全路径
例如 : E:\eclipseM9/workspace/tree/WEB-INF/classes/
 
这个方法也可以不在web环境里确定路径,比较好用
 
3.request.getContextPath();
获得web根的上下文环境
如 /tree
tree是我的web项目的root context 
 
4.在Application中:

System.getProperty("user.dir")

在Servlet中:

ServletContext servletContext = config.getServletContext();
String rootPath = servletContext.getRealPath("/");

在jsp中:

application.getRealPath("")

原创粉丝点击