当前class文件的路径

得到web获取服务器端的地址 url
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"



关于绝对路径和相对路径:
绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例如:C:xyz est.txt 代表了test.txt文件的绝对路径。http://www.sun.com/index.htm也代表了一个URL绝对路径。相对路径:相对与某个基准目录的路径。包含Web的相对路径(HTML中的相对目录),例如:在Servlet中,"/"代表Web应用的跟目录。和物理路径的相对表示。例如:"./" 代表当前目录,"../"代表上级目录。这种类似的表示,也是属于相对路径。另外关于URI,URL,URN等内容,请参考RFC相关文档标准。RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,(http://www.ietf.org/rfc/rfc2396.txt)2.关于JSP/Servlet中的相对路径和绝对路径。2.1服务器端的地址服务器端的相对地址指的是相对于你的web应用的地址,这个地址是在服务器端解析的(不同于html和javascript中的相对地址,他们是由客户端浏览器解析的)

第一种:
File f = new File(this.getClass().getResource("/").getPath());
System.out.println(f);
结果:
C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin
获取当前类的所在工程路径;
如果不加“/”
File f = new File(this.getClass().getResource("").getPath());
System.out.println(f);
结果:
C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin\com\test
获取当前类的绝对路径;

第二种:
File directory = new File("");//参数为空
String courseFile = directory.getCanonicalPath() ;
System.out.println(courseFile);
结果:
C:\Documents and Settings\Administrator\workspace\projectName
获取当前类的所在工程路径;

第三种:
URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt");
System.out.println(xmlpath);
结果:
file:/C:/Documents%20and%20Settings/Administrator/workspace/projectName/bin/selected.txt
获取当前工程src目录下selected.txt文件的路径

第四种:
System.out.println(System.getProperty("user.dir"));
结果:
C:\Documents and Settings\Administrator\workspace\projectName
获取当前工程路径

第五种:
System.out.println( System.getProperty("java.class.path"));
结果:
C:\Documents and Settings\Administrator\workspace\projectName\bin
获取当前工程路径
==================

ClassLoader提供了两个方法用于从装载的类路径中取得资源:
Java代码 
public URL getResource(String name); 
public InputStream getResourceAsStream(String name);  


这里name是资源的类路径,它是相对与“/”根路径下的位置。getResource得到的是一个URL对象来定位资源,而getResourceAsStream取得该资源输入流的引用保证程序可以从正确的位置抽取数据。


但当我第一次调用这两个方法的时候,却没能取得我想要的资源。原来真正使用的不是ClassLoader的这两个方法,而是Class的 getResource和getResourceAsStream方法,因为Class对象可以从你的类得到(如YourClass.class或 YourClass.getClass()),而ClassLoader则需要再调用一次YourClass.getClassLoader()方法,但 根据JDK文档的说法,Class对象的这两个方法其实是“委托”(delegate)给装载它的ClassLoader来做的,所以只需要使用 Class对象的这两个方法就可以了。

       结论: 调用如下代码得到正解。
Java代码 
this.getClass.getResourceAsStream(String name); 
This.class.getResourceAsStream(name);

getResourceAsStream
public InputStream getResourceAsStream(String name)查找具有给定名称的资源。查找与给定类相关的资源的规则是通过定义类的 class loader 实现的。此方法委托此对象的类加载器。如果此对象通过引导类加载器加载,则此方法将委托给 ClassLoader.getSystemResourceAsStream(java.lang.String)。
在委托前,使用下面的算法从给定的资源名构造一个绝对资源名:

如果 name 以 '/' 开始 ('\u002f'),则绝对资源名是 '/' 后面的 name 的一部分。
否则,绝对名具有以下形式:
   modified_package_name/name
其中 modified_package_name 是此对象的包名,该名用 '/' 取代了 '.' ('\u002e')。


参数:
name - 所需资源的名称
返回:
一个 InputStream 对象;如果找不到带有该名称的资源,则返回 null
抛出:
NullPointerException - 如果 name 是 null

=========================
当前class文件的路径
/*
* Copyright (c); 2002-2003 by OpenSymphony
* All rights reserved.
*/ 
package com.opensymphony.oscache.util; 
 
 
/**
* <p>This code is borrowed directly from OSCore, but is duplicated
* here to avoid having to add a dependency on the entire OSCore jar.</p>
*
* <p>If much more code from OSCore is needed then it might be wiser to
* bite the bullet and add a dependency.</p>
*/ 
public class ClassLoaderUtil { 
    /**
     * Load a class with a given name.
     *
     * It will try to load the class in the following order:
     * <ul>
     *  <li>From Thread.currentThread();.getContextClassLoader();
     *  <li>Using the basic Class.forName();
     *  <li>From ClassLoaderUtil.class.getClassLoader();
     *  <li>From the callingClass.getClassLoader();
     * </ul>
     *
     * @param className The name of the class to load
     * @param callingClass The Class object of the calling object
     * @throws ClassNotFoundException If the class cannot be found anywhere.
     */ 
    public static Class loadClass(String className, Class callingClass); throws ClassNotFoundException { 
        try { 
            return Thread.currentThread();.getContextClassLoader();.loadClass(className);; 
        } catch (ClassNotFoundException e); { 
            try { 
                return Class.forName(className);; 
            } catch (ClassNotFoundException ex); { 
                try { 
                    return ClassLoaderUtil.class.getClassLoader();.loadClass(className);; 
                } catch (ClassNotFoundException exc); { 
                    return callingClass.getClassLoader();.loadClass(className);; 
                } 
            } 
        } 
    } 



===================

(1)、request.getRealPath("/");//不推荐使用获取工程的根路径
(2)、request.getRealPath(request.getRequestURI());//获取jsp的路径,这个方法比较好用,可以直接在servlet和jsp中使用
(3)、request.getSession().getServletContext().getRealPath("/");//获取工程的根路 要用这种 ,这个方法比较好用,可以直接在servlet和jsp中使用
(4)、 this.getClass().getClassLoader().getResource("").getPath();//获取工程classes 下的路径,这个方法可以在任意jsp,servlet,java文件中使用,因为不管是jsp,servlet其实都是java程序,都是一个 class。所以它应该是一个通用的方法。


0、关于绝对路径和相对路径
1.基本概念的理解绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例如:C:xyz est.txt 代表了test.txt文件的绝对路径。http://www.sun.com/index.htm也代表了一个URL绝对路径。相对路径:相对与某个基准目录的路径。包含Web的相对路径(HTML中的相对目录),例如:在Servlet中,"/"代表Web应用的跟目录。和物理路径的相对表示。例如:"./" 代表当前目录,"../"代表上级目录。这种类似的表示,也是属于相对路径。另外关于URI,URL,URN等内容,请参考RFC相关文档标准。RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,(http://www.ietf.org/rfc/rfc2396.txt)2.关于JSP/Servlet中的相对路径和绝对路径。 2.1服务器端的地址服务器端的相对地址指的是相对于你的web应用的地址,这个地址是在服务器端解析的(不同于html和javascript中的相对地址,他们是由客户端浏览器解析的)
1、request.getRealPath
方法:request.getRealPath("/")
得到的路径:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\
方法:request.getRealPath(".")
得到的路径:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\.
方法:request.getRealPath("")
得到的路径:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest
request.getRealPath("web.xml")
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\web.xml
2、request.getParameter("");
    ActionForm.getMyFile();
方法:String filepath = request.getParameter("myFile");
得到的路径:D:\VSS安装目录\users.txt
方法:String filepath = ActionForm.getMyFile();
得到的路径:D:\VSS安装目录\users.txt

--------------------------------------------------
strutsTest 为工程名
myFile 在ActionForm中,为private String myFile;
在jsp页面中:为<html:file property="myFile"></html:file>
--------------------------------------------------

3、获得系统路径
在Application中:
System.getProperty("user.dir")

在Servlet中:
ServletContext servletContext = config.getServletContext();
String rootPath = servletContext.getRealPath("/");

在jsp中:
application.getRealPath("")

4、其他1

1.可以在servlet的init方法里
String path = getServletContext().getRealPath("/");
这将获取web项目的全路径
例如 :E:\eclipseM9\workspace\tree\
tree是我web项目的根目录
2.你也可以随时在任意的class里调用
this.getClass().getClassLoader().getResource("").getPath();
这将获取 到classes目录的全路径
例如 : /D:/workspace/strutsTest/WebRoot/WEB-INF/classes/

还有 this.getClass().getResource("").getPath().toString();
这将获取 到 /D:/workspace/strutsTest/WebRoot/WEB-INF/classes/bl/

这个方法也可以不在web环境里确定路径,比较好用
3.request.getContextPath();
获得web根的上下文环境
如 /tree
tree是我的web项目的root context



5、其他2

java获取路径几种途径- -
jdk如何判断程序中的路径呢?一般在编程中,文件路径分为相对路径和绝对路径,绝对路径是比较好处理的,但是不灵活,因此我们在编程中对文件进行操作的时候,一般都是读取文件的相对路径,
相对路径可能会复杂一点,但是也是比较简单的,相对的路径,主要是相对于谁,可以是类加载器的路径,或者是当前 java文件下的路径,在jsp编程中可能是相对于站点的路径,相对于站点的路径,我们可以通过 getServletContext().getRealPath("\") 和request.getRealPath("\"):这个是取得站点的绝对路径; 而getContextPath():取得站点的虚拟路径;
2:class.getClassLoader.getPath():取得类加载器的路径:什么是类加载器呢?一般类加载器有系统的和用户自己定义的;系统的ClassLoader就是jdk提供的,他的路径就是jdk下的路径,或者在 jsp编程,比如Tomcat ,取得的类加载器的位置就是tomaca自己设计的加载器的路径,
明白了这些之后,对于文件路径的操作就会相当的清楚,我们在编程的时候,只要想清楚我们所操作的文件是相对于什么路径下的,取得相对路径就可以了.

6、总结
1、获取web服务器下的文件路径
request.getRealPath("/")
application.getRealPath("")【jsp中 】
ServletContext().getRealPath("")
System.getProperty("user.dir")【不同位置调用,获取的路径是动态变化的】

2、获取本地路径
jsp中,<html:file property="myFile"/>
request.getParameter("myFile");
ActionForm.getMyFile();
获取的值相同:如D:\VSS安装目录\users.txt
*********************************
this.getClass().getClassLoader().getResource("").getPath();
==/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/
this.getClass().getResource("").getPath().toString();
==/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/bl/

3、获取相对路径
request.getContextPath();
如:/strutsTest

===============

尝试用DOM4j解析spring配置文件时,第一步读取文件时,获取路径就遇到了问题,。。。经过google了n+log n 次个页面,才算有了个粗浅的认识,下面就让我用简短的话语来总结一下(好像这段就全是废话。。。)。。。
1、spring的配置文件存放位置由web.xml里的contextConfigLocation来确定,一般是放在web-inf或者是src根目录下
2、关于src文件夹里的文件的发布:source folder下的.java文件,生成的.class文件放在output folder中。而将source folder中的非.java文件直接拷贝到output folder(eclipse会直接拷贝全部的非.java文件,intellij IDEA可以配置拷贝哪些扩展名的文件)。 output文件夹一般指的是c/s的bin和b/s的classes。
3、用SAXReader.reader读取时需要知道文件的路径 。
我列出一段代码,大家感受一下吧

getclass()是当前的类实例,得到的是src下当前类的目录;getclassloader()是类的装载器,得到的是src根目录。"/"表示的是根目录。
web-inf目录如何取得还在摸索中,各位有知道的,请不吝赐教。
最后贴一篇我感觉总结得很好的文章:
http://imyself.javaeye.com/blog/460706
再来一篇 类加载路径 原理的文章 jwitch:
http://www.blogjava.net/Unmi/archive/2007/09/10/144101.html
还有这篇也需要研究一下:
http://www.javaeye.com/topic/7871


System.out.println(this.getClass().getClassLoader().getResource("com/lavasoft/res/a.txt"));
System.out.println(this.getClass().getResource("/com/lavasoft/res/a.txt"));
System.out.println(this.getClass().getResource("").getPath());
System.out.println(this.getClass().getResource("/").getPath());
System.out.println(this.getClass().getClassLoader().getResource("").getPath());
System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());
System.out.println(System.getProperty("user.dir"));


============================

当前class文件的路径_第1张图片

你可能感兴趣的:(Class文件)