Java中实现获取路径的方法汇总
作者:hebedich 时间:2022-12-19 08:10:54
一、 java文件中获得路径
Thread.currentThread().getContextClassLoader().getResource("") //获得资源文件(.class文件)所在路径
ClassLoader.getSystemResource("")
Class_Name.class.getClassLoader().getResource("")
Class_Name.class .getResource("/")
Class_Name.class .getResource("") // 获得当前类所在路径
System.getProperty("user.dir") // 获得项目根目录的绝对路径
System.getProperty("java.class.path") //得到类路径和包路径
打印输出依次如下:
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/com/xml/imp/
F:work_litaouri_test
F:work_litaouri_testWebContentWEB-INFclasses;F:work_litaouri_testWebContentWEB-INFlibdom4j.jar
二、 JSP中获得当前应用的相对路径和绝对路径
根目录所对应的绝对路径:request.getRequestURI()
文件的绝对路径 :application.getRealPath(request.getRequestURI());
当前web应用的绝对路径 :application.getRealPath("/");
取得请求文件的上层目录:new File(application.getRealPath(request.getRequestURI())).getParent()
三、Servlet中获得当前应用的相对路径和绝对路径
根目录所对应的绝对路径:request.getServletPath();
文件的绝对路径 :request.getSession().getServletContext().getRealPath(request.getRequestURI())
当前web应用的绝对路径 :servletConfig.getServletContext().getRealPath("/");
(ServletContext对象获得几种方式:
javax.servlet.http.HttpSession.getServletContext()
javax.servlet.jsp.PageContext.getServletContext()
javax.servlet.ServletConfig.getServletContext()
)
以上所述就是本文的全部内容了,希望大家能够喜欢。
请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JavaSE static final及abstract修饰符实例解析
![](https://img.aspxhome.com/file/2023/9/62129_0s.png)
关于@RequestBody和@RequestParam注解的使用详解
![](https://img.aspxhome.com/file/2023/4/62654_0s.jpg)
Java中的CAS和ABA问题说明
![](https://img.aspxhome.com/file/2023/7/66637_0s.png)
resty mail的简单发送邮件方法
C#带你玩扫雷(附源码)
![](https://img.aspxhome.com/file/2023/8/70398_0s.png)
浅析java移位符的具体使用
springboot整合solr的方法详解
![](https://img.aspxhome.com/file/2023/0/61580_0s.png)
java锁synchronized面试常问总结
![](https://img.aspxhome.com/file/2023/7/57917_0s.png)
JDBC核心技术详解
![](https://img.aspxhome.com/file/2023/9/63169_0s.png)
java中方法递归的简单示例
![](https://img.aspxhome.com/file/2023/1/66041_0s.png)
java中的String定义的字面量最大长度是多少
![](https://img.aspxhome.com/file/2023/9/61959_0s.png)
Java中的复合数据类型
![](https://img.aspxhome.com/file/2023/3/69273_0s.png)
mybatis原理概述入门教程
Java Springboot的目的你知道吗
Java8中关于Function.identity()的使用
![](https://img.aspxhome.com/file/2023/1/67161_0s.png)
一文总结Java获取文件后缀名的所有方法
java ThreadPoolExecutor线程池拒绝策略避坑
java在网页上面抓取邮件地址的方法
Java 如何实现一个http服务器
![](https://img.aspxhome.com/file/2023/2/61292_0s.png)