获取Web工程的物理路径
原创
©著作权归作者所有:来自51CTO博客作者踏行天下的原创作品,请联系作者获取转载授权,否则将追究法律责任
java 获取Web项目的物理路径,以前也用过不过忘了,现在写在这里记录下免得以后忘了好找,哈哈...
方法有好多种,以下第一种,是我用过的且通过了。
package test;
public class Path {
/**
* @param args
*/
void printpath(){
String path=this.getClass().getResource("/").getPath();//得到d:/tomcat/webapps/工程名WEB-INF/classes/路径
path=path.substring(1, path.indexOf("WEB-INF/classes"));//从路径字符串中取出工程路劲
System.out.println(path);
}
public static void main(String[] args) {
Path p=new Path();
p.printpath();
}
}
注意:在jsp页面中同样可以使用
输出:d:/tomcat/webapps/工程名/
以下的与这相关的参考:
public class CreateXmlAction extends HttpServlet { private ServletConfig config; public void init(ServletConfig config) throws ServletException { this.config = config; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = config.getServletContext().getRealPath("/"); }} 或者直接在继承了HttpServlet的Servlet中写: String filePath=this.getServletConfig().getServletContext().getRealPath("/"); |
Class clazz = test.Test.class; String name = clazz.getName().replace('.', '/'); URL url = Thread.currentThread().getContextClassLoader().getResource(name); 这个时候会得到"file:/D:/java/test/Test.class"这样的url,你只要去掉file:/即可 |
import java.io.File; public class Test { public static void main(String[] args) throws Exception { System.out.println(Thread.currentThread().getContextClassLoader().getResource("")); System.out.println(Test.class.getClassLoader().getResource("")); System.out.println(ClassLoader.getSystemResource("")); System.out.println(Test.class.getResource("")); System.out.println(Test.class.getResource("/")); //Class文件所在路径 System.out.println(new File("/").getAbsolutePath()); System.out.println(System.getProperty("user.dir")); } } |