Java各种路径和参数

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运行时环境版本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值