似乎Java获取路径不是一个简单的问题,现在就简单整理一下资料吧。
Java获取项目路径的方法不少,但是问题也不少。
1、通过Request对象获得
方法request.getRealPath(String path)
此方法通过传入项目的资源相对路径可以返回一个绝对的路径,但是注释中显示:
Deprecated. As of Version 2.1 of the Java Servlet API, use ServletContext.getRealPath
instead.
不再建议使用此方法,而用ServletContext.getRealPath 代替,所以此方法不详说。
2、通过ServletContext.getRealPath(String path)对象获得
就上面所说的getRealPath(String path),这个方法在Web应用中是可以得到项目中的资源路径的,这个可以用,但是有一个情况值得注意,就是当你的项目被打包成war的时候,这个时候通过获得的路径去访问就会出错,它可能返回null或类似“myserverstage_appsdir_test_wartest.war!WEB-INFconfig….”这样的内容,war里面的文件是不能用路径去访问的。如果你仅仅是读取资源文件,有更好的方法,不必获取路径,请往下看一下ServletContext的其他方法。
***似乎Tomcat用war部署会自动解压,这个应该可以用?是不是有些服务器不会解压所以没法用?这个以后了解清楚后更新。***
3、通过ServletContext.getResource(String path)得到资源URL
这个方法可以得到项目中资源的URL对象,然后我们可以通过RUL得到相应的资源,这个是靠普的。URL转为File,如果你想要得到InputStream,可用下面的方法。
4、ServletContext.getResourceAsStream(String path)
这个方法返回InputStream,没有任何问题。
如果你是要获得项目里的资源,只推荐使用ServletContext的getResource和getResourceAsStream方法,关于更详细的内容,请看引用。
附:
一、Struts2中获取ServletContext对象的方法
1、Action继承org.apache.struts2.util.ServletContextAware接口
代码如下:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import javax.servlet.ServletContext; import org.apache.struts2.util.ServletContextAware; import com.opensymphony.xwork2.Action; public class ContextAction implements ServletContextAware,Action { ServletContext context; public String execute() throws Exception { return SUCCESS; } public void setServletContext(ServletContext context) { this.context = context; } } |
如果Action继承了这个接口,Servlet Config拦截器会为context变量添加ServletContext对象引用。
2、通过ServletActionContext类获取
代码如下:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.Action; public class ContextAction implements Action { public String execute() throws Exception { ServletContext context = ServletActionContext.getServletContext(); return SUCCESS; } } |
二、URL转换成File
1、URL.getFile()
0 1 2 3 |
File f = new File(URLDecoder.decode(url.getFile(), "UTF-8")); |
2、URL.toURI()
0 1 2 3 |
File file = new File(url.toURI()); |
How To Get The ServletContext In Struts 2