Web应用获取文件路径的方法

时间:2023-03-10 02:22:58
Web应用获取文件路径的方法

拥有 HttpServletRequest req 对象

req.getSession().getServletContext().getRealPath("/")   ---------》当前项目的根路径   比如 我的test项目的目录 D:\develop_software\apache-tomcat-8.0.9\webapps\test

拥有 ServletContextEvent  sce对象

sce.getServletContext().getRealPath("/")                 ---------》当前项目的根路径

任意类

Thread.currentThread().getContextClassLoader().getResource("") 来得到当前的classpath的绝对路径的URI表示法。

File f= new File(Thread.currentThread().getContextClassLoader().getResource("111.txt").getFile());