1.JSP中获得当前应用的相对路径和绝对路径:
根目录所对应的绝对路径:request.getRequestURI()
文件的绝对路径:application.getRealPath(request.getRequestURI());
当前web应用的绝对路径 :application.getRealPath("/");
取得请求文件的上层目录:new File(application.getRealPath(request.getRequestURI())).getParent();
2.Servlet中获得当前应用的相对路径和绝对路径
根目录所对应的绝对路径:request.getServletPath();
文件的绝对路径:request.getSession().getServletContext().getRealPath
(request.getRequestURI());
当前web应用的绝对路径 :servletConfig.getServletContext().getRealPath("/");
ServletContext对象获得几种方式:
Javax.servlet.http.HttpSession.getServletContext()
Javax.servlet.jsp.PageContext.getServletContext()
Javax.servlet.ServletConfig.getServletContext()
3.获取当前class所处的jar包路径:
Java代码URL uri = clazz.getProtectionDomain().getCodeSource().getLocation();
String path = uri.getPath();
File jarFile = new File(path);
4.windows下获取桌面文件夹:
Java代码FileSystemView fileSystemView =FileSystemView.getFileSystemView();File[] desktops = fileSystemView.getRoots();
5.获取我的文档:
Java代码FileSystemView fileSystemView =FileSystemView.getFileSystemView();
File f = fileSystemView.getDefaultDirectory();
上面两个方案,在vista下无效,因为vista的桌面、我的文档路径跟xp,2000不一样。
6.服务器中的Java类获得当前路径
(1)Weblogic
WebApplication的系统文件根目录是weblogic安装所在根目录
例如:如果你的weblogic安装在c:/bea/weblogic700.....
那么,你的文件根路径就是c:/.
所以,有两种方式能够让你访问你的服务器端的文件:
a.使用绝对路径:
比如将你的参数文件放在c:/yourconfig/yourconf.properties,
直接使用 new FileInputStream("yourconfig/yourconf.properties");
b.使用相对路径:
相对路径的根目录就是你的webapplication的根路径,即WEB-INF的上一级目录,将你的参数文件放在yourwebapp/yourconfig/yourconf.properties,
这样使用:
new FileInputStream("./yourconfig/yourconf.properties");
这两种方式均可,自己选择。
(2)Tomcat
在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin
7.获取执行文件当前路径:
Java代码String dir = System.getProperty("user.dir");
通过System.getProperty()还可以得到很多环境参数,如下是一个整理过的表。
java.version Java运行时环境版本
Java各种路径和参数
最新推荐文章于 2024-08-28 01:27:08 发布