很多情况下,我们需要在JavaBean、Servlet中获得当前的目录路径,比如载入配置文件,上传文件到服务器等。

1.载入jdbc.properties

1)ClassLoader的getResourceAsStream("XXX")

InputStream in=XXX.class.getClassLoader().getResourceAsStream("jdbc.properties"); 
 getResourceAsStream()会到classes目录下找jdbc.properties文件,所以在工程项目中,我们一般把它放在src目录下。

2)Class.getResourceAsStream("/XXX")

XXX.class.getResourceAsStream("/jdbc.properties");

两种方式的共同点就是:jdbc.properties都应该在classes下,也就是项目的src目录

不同点就是:ClassLoader.getResourceAsStream(“XXX”)中参数不以"/"开头,而Class.getResourceAsStream("/XXX") 终参数以"/"开头

2.在Javabean中获得路径
1)获得当前类XXX.class文件的URI目录,不包括自己:XXX.class.getResource("")
如:在类com.test.XXX中取得项目的根绝对路径

URL url=XXX.class.getResource(""); 
 String filename=url.getFile(); 
 String projectRootPath=new File(filename,"../../../../").getCanonicalPath(); 
 //main函数中测试 
e:/d:/workspace/testproject/build/calsses/com/test/ 
 //projectRootPath:d:/workspace/testproject 
 //tomcat中测试 
 //filename:/d:/tomcat/webapps/testproject/WEB-INF/calsses/com/test/ 
 //projectRootPath:d:/tomcat/webapps/testproject

2)获得的是当前的classpath的绝对URI路径:XXX.class.getResource("/")
如:在类com.test.XXX中取得项目的根绝对路径

URL url=XXX.class.getResource("/"); 
 String filename=url.getFile(); 
 String projectRootPath=new File(filename,"../../").getCanonicalPath(); 
 //main函数中测试 
 //filename:/d:/workspace/testproject/build/calsses/ 
 //projectRootPath:d:/workspace/testproject 
 //tomcat中测试 
 //filename:/d:/tomcat/webapps/testproject/WEB-INF/calsses/ 
 //projectRootPath:d:/tomcat/webapps/testproject

3)获得的是当前ClassPath的绝对URI路径: //推荐使用

Thread.currentThread().getContextClassLoader().getResource("");

4)获得的是当前ClassPath的绝对URI路径:

XXX.class.getClassLoader().getResource("");

5)获得的是当前ClassPath的绝对URI路径: //推荐使用

ClassLoader.getSystemResource("");

6)当前用户目录的相对路径:System.getProperty("user.dir") //不推荐使用
3.在servlet中获得路径
1)获得相对路径:

this.getServletContext().getResource("/").getPath(); 
 //输出:/localhost/testproject/

2)

String strPath2=this.getServletContext().getRealPath("/"); 
 //输出:d:/tomcat/webapps/testproject/

比较简单,就不在累述了,而在很多
情况下,我们需要把我们的class打包成jar文件,进行使用,这时就会发现,我们先前如果没有考虑到这些,可能就行不通了,那么,该如何解决呢?方法如下

有如下路径 :

Web-info--|-->classes--->conf-->config.properties 
 |-->lib

此时加入我们需要读取config.properties,在不使用jar包时,使用如下方式读取,不失为一种方法:

File f = new File(this.getClass().getResource("/").getPath()); 
f = new File(f.getPath() + "/conf/config.properties");

注:f.getPath()即为当class所在的绝对路径。如:c:\javasrc\web-inf\classes
然后,对文件对象进行处理,就能把配置信息读取出来了,但是加入如上class被打包成jar文件,那么,在程序执行到这里时,就会无法找到配置文件,那么该如何处理呢?
处理方法如下:

String s_config="conf/config.properties"; 
 InputStream in = ClassLoader.getSystemResourceAsStream(s_config); 
if( in == null ){ 
 System.out.println( " 打开 " + s_config + "失败!" ); 
}else 
{ 
Properties properties = new Properties(); 
properties.load(in); 
// 
//接下来就可以通过properties.getProperty(String obj)方法对进行配置信息读取了 
}