Java获取程序或项目路径的常用方法

在写java程序时不可避免要获取文件的路径,比较常用的方法有:


1 在任意的class里调用:
this.getClass().getClassLoader().getResource("/").getPath();
//这将获取 到classes目录的全路径
//如 : E:eclipseM9/workspace/tree/WEB-INF/classes/

这个方法也可以不在web环境里确定路径,比较好用


2 在servlet的init方法里
String path = getServletContext().getRealPath("/");
//这将获取web项目的全路径
//例如 :E:eclipseM9workspace	ree
//tree是我web项目的根目录


3.获得web根的上下文环境
request.getContextPath();
//如 /tree 是我的web项目的root context
/*jsp 取得当前目录的路径*/
path=request.getRealPath("");
/*得到jbossWEB发布临时目录 warUrl=.../tmp/deploy/tmp14544test-exp.war/*/
path=C:jboss-4.0.5.GAserverdefault	mpdeploy	mp14544test-exp.war
String   path   =   (String)request.getContextPath();
/*得到项目(test)应用所在的真实的路径 path=/test*/ 
String     path     =   request.getRequestURI();
/*得到应用所在的真实的路径 path=/test/admin/admindex.jsp*/
String   savePath=request.getRealPath(request.getServletPath());
/*得到当前文件的磁盘绝对路径*/  
//JAVA 取得当前目录的路径
File   file=new   File(".");   
String path=file.getAbsolutePath();
                path=file.getPath();
/*得到jboss运行目录 path=C:jboss-4.0.5.GAin*/



 

原文地址:https://www.cnblogs.com/james1207/p/3275784.html