JAVA Web获取路径几种方式

来源:互联网 发布:制作app直播软件 编辑:程序博客网 时间:2024/05/17 02:40

环境介绍
class文件路径为:D:\Users\Administrator\IdeaProjects\Angular\hrmapp\src\main\java\com\hrm\controller\DocumentController.java
字节码文件路径为:D:\Users\Administrator\IdeaProjects\Angular\hrmapp\target\classes\com\hrm\controller\DocumentController.class
tomcat目录为:

D:\tomcat\TOMCAT\apache-tomcat-7.0.67

**IDE: Intellij IDEA
Web容器:tomcat
项目类型:Maven**

方式一,通过request获取

        String savedDir1 = request.getSession().getServletContext().getRealPath(""); 

结果为:D:\Users\Administrator\IdeaProjects\Angular\hrmapp\target\hrmapp

方式二,通过当前线程获取

     ```     URL url = Thread.currentThread().getContextClassLoader().getResource("");     ```     结果为:file:/D:/Users/Administrator/IdeaProjects/Angular/hrmapp/target/hrmapp/WEB-INF/classes/

方式三,通过new文件获取

File file1 = new File("");String canonicalPath = file1.getCanonicalPath();String absolutePath = file1.getAbsolutePath();

结果:D:\tomcat\TOMCAT\apache-tomcat-7.0.67\bin

方式四,通过当前类获取

    String path1 = this.getClass().getClassLoader().getResource("").getPath();

结果: /D:/Users/Administrator/IdeaProjects/Angular/hrmapp/target/hrmapp/WEB-INF/classes/

方式五,通过当前类获取(第二种)

    String path = this.getClass().getResource("").getPath();

结果: /D:/Users/Administrator/IdeaProjects/Angular/hrmapp/target/hrmapp/WEB-INF/classes/com/hrm/controller/

原创粉丝点击