1 获取当前项目所在路径
// 获取当前项目根路径
String dir = System.getProperty("user.dir");
获取resource 下静态资源路径
public static String getStaticPath(){
URL resource = Thread.currentThread().getContextClassLoader().getResource("static");
assert resource != null;
return resource.getPath();
}
public static String getStaticPath2(){
URL resource = StaticUtil.class.getClassLoader().getResource("static");
assert resource != null;
return resource.getPath();
}
3 直接获取resource 下的资源
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
// 获取resource 下的资源
Resource resource = new ClassPathResource("license.xml");
System.out.println(resource.getURL().getPath());
4 注意(线上最好不要使用getResource)
使用getResource来读取resources文件夹下的文件,但是这个方法没有办法读取压缩文件里的路径,而jar本质来说是一个压缩包.所以在线上环境使用getResource时会报错
file:/D:/ItemProjects/IdeaProjects/MT-learn-server/target/mtlearnserver-0.0.1-SNAPSHOT-exec.jar!/BOOT-INF/classes!/static
版权声明:本文为weixin_43702146原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。