您的位置:首页 > 编程语言 > Java开发

JSP、Java 获取当前绝对路径

2007-08-29 18:05 429 查看
在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类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: