java项目测试或者不使用request,如何获取webroot路径


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是有这个文件的,然后输出。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM