有一个文件位于 src/main/resources/test.txt
有一个类位于 src/main/java/com/qunar/MyClass.java
String path = Demo.class.getClassLoader().getResource("test.txt").getPath();System.out.println(path);
可以直接获取文件路径
而classpath可以通过如下代码获取
MyClass.class.getClassLoder().getResource("").getPath();
通过当前类的加载路径使用相对路径来获取资源地址
MyClass.class.getResource(FILE_NAME).getPath()
此时的路径是相对于MyClass这个类在运行时路径而言的,
test.txt和MyClass并不在一个层级,因为MyClass之前还有两个包
可以如下解决:
// 这种方法相当于使用绝对运行时路径
MyClass.class.getResource(File.separator + "FILE_NAME").getPath();// 这种方法相当于使用相对MyClass的运行时路径
MyClass.class.getResource(".." + File.separator + ".." + File.separator + FILE_NAME).getPath();