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;

}

输出结果为:

/reflectWeb

D:\code\studyCode\/reflectWeb\upload\

D:\code\studyCode\/reflectWeb\upload\fe6156bb-932f-41ad-9a1c-b20cd8ac06e5.jpg**********

2、其他获取资源的路径的方法

String path = super.getServletContext().getRealPath("/") + File.separatorthis.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);

输出结果为:

  1. #####获取当前classpath的绝对url路径####
  2. /D:/code/studyCode/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/reflectWeb/WEB-INF/classes/
  3. /D:/code/studyCode/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/reflectWeb/WEB-INF/classes/
  4. #####获取当前类的加载目录,如果有“/”获取当前类的所在工程路径####
  5. /D:/code/studyCode/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/reflectWeb/WEB-INF/classes/cn/mldn/servlet/
  6. /D:/code/studyCode/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/reflectWeb/WEB-INF/classes/
  7. #####项目绝对路径####
  8. /D:/code/studyCode/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/reflectWeb/WEB-INF/classes/
  9. #####当前文件路径####
  10. D:\code\studyCode\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\reflectWeb\
  11. D:\code\studyCode\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\reflectWeb\
  12. D:\code\studyCode\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\reflectWeb\\upload\
  13. *********

猜你喜欢

转载自blog.csdn.net/OldStreet61/article/details/81114798