JSP、Java 获取当前绝对路径

在eclipse或者其它.class文件没有被打包的情况下,使用如下语句可以获得.class文件的绝对路径:

String classFilePath = clazz.class.getResource("").getPath();

当.class文件被打进jar包之后,上面这条语句就要报错了。这时你能做的就是去获取.class文件所在的jar的绝对路径:

String jarFilePath = clazz.class.getProtectionDomain().getCodeSource().getLocation().getFile();  
jarFilePath = java.net.URLDecoder.decode(jarFilePath, "UTF-8");


JSP:

String sLocalRealPath = application.getRealPath("/").replace('\\', '/');
if (sLocalRealPath != null && !sLocalRealPath.endsWith("/"))
{
    sLocalRealPath.concat("/");    //避免 WebLogic 和 WebSphere 不一致
}


 Java:

String sClassRealPath = new String("");
//前面会多返回一个"/", 例如  /D:/test/WEB-INF/, 奇怪, 所以用 substring()
sClassRealPath = this.getClass().getResource("/").getPath().substring(1).replaceAll("//", "/");
System.out.println(sClassRealPath);



1.如何获得当前文件路径
常用:
(1).Test.class.getResource("")
得到的是当前类FileTest.class文件的URI目录。不包括自己!
(2).Test.class.getResource("/")
得到的是当前的classpath的绝对URI路径。
(3).Thread.currentThread().getContextClassLoader().getResource("")
得到的也是当前ClassPath的绝对URI路径。
(4).Test.class.getClassLoader().getResource("")
得到的也是当前ClassPath的绝对URI路径。
(5).ClassLoader.getSystemResource("")
得到的也是当前ClassPath的绝对URI路径。
尽量不要使用相对于System.getProperty("user.dir")当前用户目录的相对路径,后面可以看出得出结果五花八门。
(6) new File("").getAbsolutePath()也可用。


2.Web服务器
(1).Tomcat
在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin
(2).Resin
不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET
的路径为根.比如用新建文件法测试File f = new File("a.htm");
这个a.htm在resin的安装目录下
(3).如何读文件
使用ServletContext.getResourceAsStream()就可以
(4).获得文件真实路径
String file_real_path=ServletContext.getRealPath("mypath/filename");?
不建议使用request.getRealPath("/");
3.文件操作的类,不建议使用,可以使用commons io类



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值