在项目里面经常会遇到获得文件路径的问题,有些时候写死文件路径不是很恰当,这个时候就可以通过获得当前的Class的路径来组合文件的路径,以下是一些经常使用的方法,特意总结如下:
本人系统为linux,我的文件路径为
java文件:/home/bokee/apache-tomcat-7.0.29/webapps/SSH/WEB-INF/classes/com/ssh/client/FilePathDemo.java
jsp:/home/bokee/apache-tomcat-7.0.29/webapps/SSH/path.jsp
servlet:/home/bokee/apache-tomcat-7.0.29/webapps/SSH/WEB-INF/classes/com/ssh/servlet/PathServlet.java
一在Class里面:
1.通过Class:
this.getClass().getClassLoader().getResource("").getPath():/home/bokee/apache-tomcat-7.0.29/webapps/SSH/WEB-INF/classes/
this.getClass().getClassLoader().getResource("/").getPath(): null (结果为空)
System.getProperty("user.dir"):/home/bokee/apache-tomcat-7.0.29/webapps/SSH
System.getProperty("java.class.path"):(这个是输出所有包的完整路径,太多就不写了,自己试下就做到了)
this.getClass().getResource("/"):file:/home/bokee/apache-tomcat-7.0.29/webapps/SSH/WEB-INF/classes/
this.getClass().getResource(""):file:/home/bokee/apache-tomcat-7.0.29/webapps/SSH/WEB-INF/classes/com/ssh/client/
2.通过Thread:
Thread.currentThread().getContextClassLoader().getResource("").getPath():file:/home/bokee/apache-tomcat-7.0.29/webapps/SSH/WEB-INF/classes/
在windows里面以上方法获得的结果会在路径前面多一个"/"。拼接的时候注意。
二.jsp里面:
jsp:/home/bokee/apache-tomcat-7.0.29/webapps/SSH/path.jsp
我在welcome.jsp里面写下如下代码:<html:link page="/path.jsp?key=1">path</html:link> 点击后链接到path.jsp
request.getRequestURL():http://localhost:8080/SSH/path.jsp
request.getRequestURI():/SSH/path.jsp
request.getServletPath():/path.jsp
request.getQueryString():key=1
request.getContextPath():/SSH
application.getRealPath(""):/home/bokee/apache-tomcat-7.0.29/webapps/SSH
request.getRealPath(""):/home/bokee/apache-tomcat-7.0.29/webapps/SSH