Java根据相对路径动态获取绝对路径

更新日志
  • 2021-03-02
    更新内容:
    一、方式三:通过当前线程获取
    

一、获取项目的src目录下的资源

方式一:通过类装载器获取

  • 所以通过src下的某个类获得类装载器对象后,即可获取src下任意文件的URL;

    // 获取当类的类装载器 DB是你当前类的类名
    ClassLoader loader = DB.class.getClassLoader(); 
    // 获取文件的绝地位置 
    URL resource = loader.getResource("jdbc.properties"); 
    // 获取文件路径
    String path = resource.getPath(); 
    

方式二:通过请求的servlet获取web目录路径(workspaace)

  • 在HttpServlet中。
// 获取当前servlet的ServletContext
ServletContext servletContext = this.getServletConfig().getServletContext();
// 获取当前servlet文件所在的工作目录
String work_dir = servletContext.getRealPath("/");
// 以文件对象来,根据当前servlet的路径向上查找父目录,找到项目目录所在位置
File root_file = new File(work_dir).getParentFile().getParentFile().getParentFile();
// 获取项目目录的绝对路径
String root_dir = root_file.getAbsolutePath();
// 根据项目目录的绝对路径,拼接子目录
String base_dir = root_dir.concat("web");

方式三:通过当前线程获取

  • 假设当前的工程结构如下
    src
       |__main
          |__java
          |   |__com
          |       |__langkye
          |           |__Application.java
          |__resources
             |__template
             |   |__index.html
             |__application.yaml
    
  • 使用案例
    //获取 application.yaml 绝对路径
    Thread.currentThread().getContextClassLoader().getResource("application.yaml").getPath()
    //获取 index.html 绝对路径
    Thread.currentThread().getContextClassLoader().getResource("template/index.html").getPath()
    //获取 Application.java 绝对路径
    Thread.currentThread().getContextClassLoader().getResource("com/langkye/Application.java").getPath()
    


二、获取整个web项目的路径

获取web项目中文件在服务器中的真实路径,项目部署后src中的文件被编译后会被放到web/WEB-INF/classes/

ServletContext servletContext = request.getServletContext();
// web下的a.properties
String a = servletContext.getRealPath("/a.properties"); // .../web/a.properties
// web/WEB-INF下的b.properties
String b = servletContext.getRealPath("/WEB-INF/b.properties"); // .../web/WEB-INF/b.properties
// src下的c.properties
String c = servletContext.getRealPath("/WEB-INF/classes/c.properties"); // .../web/WEB-INF/classes/c.properties
原文地址:https://www.cnblogs.com/langkyeSir/p/13173361.html