以文本方式查看主题

-  课外天地 李树青  (http://www.njcie.com/bbs/index.asp)
--  JavaEE网站开发课件  (http://www.njcie.com/bbs/list.asp?boardid=20)
----  [转帖]JAVA 取得当前目录的路径  (http://www.njcie.com/bbs/dispbbs.asp?boardid=20&id=673)

--  作者:admin
--  发布时间:2009/3/24 14:41:37
--  [转帖]JAVA 取得当前目录的路径

在写java程序时不可避免要获取文件的路径...总结一下,遗漏的随时补上
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

/*jsp 取得当前目录的路径
path=request.getRealPath("");
/*得到jbossWEB发布临时目录 warUrl=.../tmp/deploy/tmp14544test-exp.war/
path=C:\\jboss-4.0.5.GA\\server\\default\\tmp\\deploy\\tmp14544test-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.GA\\bin\\


 

[此贴子已经被作者于2010-12-12 10:40:43编辑过]