黑马程序员技术交流社区

标题: 【上海校区】java获取当前项目的路径地址 [打印本页]

作者: 小影姐姐    时间: 2018-7-20 14:16
标题: 【上海校区】java获取当前项目的路径地址
1、手动拼接获取项目的绝对路径   

/**

   * 得到文件保存的路径

   *

    * @return

   */

public String getPath() {

      System.out.println("*********");

      String path1 = Thread.currentThread().getContextClassLoader().getResource("").getPath();//获取当前资源的虚拟路径

      System.out.println(path1);

      String currentProjectName = this.request.getContextPath();//获取当前项目名称

      System.out.println(this.request.getContextPath());

      int num = path1.indexOf(".metadata");

      String testPath = path1.substring(1, num).replace('/', '\\') +currentProjectName + "\\" + this.getDirectory()

           + "\\";

      System.out.println(testPath);

      File file = new File(testPath);

//判断该路径下文件是否存在,不存在则创建

      if (!file.exists()) {

        file.mkdirs();

      }

      return testPath;

}

输出结果为:/reflectWebD:\code\studyCode\/reflectWeb\upload\D:\code\studyCode\/reflectWeb\upload\fe6156bb-932f-41ad-9a1c-b20cd8ac06e5.jpg**********2、其他获取资源的路径的方法

String path = super.getServletContext().getRealPath("/") + File.separator+ this.getDirectory()

           + File.separator;

      System.out.println("#####获取当前classpath的绝对url路径####");

      System.out.println(this.getClass().getClassLoader().getResource("").getPath());

      System.out.println(this.getClass().getClassLoader().getResource("/").getPath());

      System.out.println("#####获取当前类的加载目录,如果有“/”获取当前类的所在工程路径####");

      System.out.println(this.getClass().getResource("").getPath());

      System.out.println(this.getClass().getResource("/").getPath());

      System.out.println("#####项目绝对路径####");

      System.out.println(this.getClass().getClassLoader().getResource(".").getPath());

      System.out.println("#####当前文件路径####");

      System.out.println(this.getServletContext().getRealPath("/"));

      System.out.println(super.getServletContext().getRealPath("/"));

      System.out.println(path);

输出结果为:

作者: 不二晨    时间: 2018-7-20 17:52
优秀,奈斯
作者: 小怪兽暖阳    时间: 2018-7-20 18:07
虽然还没学到,先提前关注一波

作者: 摩西摩西OvO    时间: 2018-7-23 13:31

作者: 吴琼老师    时间: 2018-7-26 15:34





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2