java 获取Web项目的物理路径,以前也用过不过忘了,现在写在这里记录下免得以后忘了好找,哈哈...
方法有好多种,以下第一种,是我用过的且通过了。
注意:在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")); } } |