1.使用jdk中的方法,然后根據項目編譯后的文件存在的位置,獲取到classes目錄,然后向上級查詢獲取
String path = EngineTest.class.getResource("/").toURI().getPath(); // /F:/eclipse2/workspace/項目/WebRoot/WEB-INF/classes/
String canonicalPath = new File(path).getParentFile().getParentFile().getCanonicalPath(); // F:\eclipse2\workspace\項目\WebRoot
System.out.println(canonicalPath);// F:\eclipse2\workspace\項目\WebRoot
WebRoot后邊 \ 這個需要自己加
2.根據System類獲取項目路徑,然后在找WebRoot路徑
Strng xiangmuPath = System.getProperty("user.dir"); // F:\eclipse2\workspace\項目
String webrootPath = xiangmuPath + "\WebRoot";
3.springboot中有很多中,這里自己用到的一種,放到templates下的文件,可以通過這種方式獲取
String path = ClassUtils.getDefaultClassLoader().getResource("templates/pdf/templateJfinal.html").getPath(); // /F:/eclipse2/workspace/demo/target/classes/templates/pdf/templateJfinal.html
4.也是springboot中的
String path2 = "/templates/pdf/templateJfinal.html";//最開始的 / 加不加都行 ClassPathResource classPathResource = new ClassPathResource(path2); try { System.out.println(classPathResource.getURL().getPath()); // /F:/eclipse2/workspace/demo/target/classes/templates/pdf/templateJfinal.html
} catch (IOException e) { e.printStackTrace(); }
ResourceUtils.getURL("uploadFile").getPath()
輸出的路徑是:/Users/renjianjun/study/ideaWorkSpace/rjj-download/uploadFile
我的uploadFile是有這個文件的,然后輸出。