很多情况下,我们需要在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,"http://www.cnblogs.com/http://www.cnblogs.com/").getCanonicalPath();
//main函数中测试
//filename:/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,"http://www.cnblogs.com/").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/