参考博客链接:https://www.cnblogs.com/ruiati/p/6225093.html
public class TestClassPathResource {
@Test
public void testResouce() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
System.out.println(loader.getResource("").getPath());
System.out.println(this.getClass().getResource("").getPath());
System.out.println(this.getClass().getResource("/").getPath());
System.out.println(System.getProperty("user.dir"));
try {
String filePath = new ClassPathResource("../resources/application.yml").getFile().getAbsolutePath();
System.out.println(filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Class.getResource("")获取的是相对于当前类的相对路径
Class.getResource("/")获取的是classpath的根路径
ClassLoader.getResource("")获取的是classpath的根路径
在创建ClassPathResource对象时,我们可以指定是按Class的相对路径获取文件还是按ClassLoader来获取。