class.getResource
class.getResource
测试用例
public static void main(String[] args) {
System.out.println(ResourceReader.class.getResource(""));
System.out.println(ResourceReader.class.getResource("/"));
System.out.println(ResourceReader.class.getResource("a.txt"));
System.out.println(ResourceReader.class.getResource("/test/a.txt"));
}
resource目录
输出
file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/utils/
file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/
null
file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/a.txt
file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/test/a.txt
- class.getResource(“”) 不带”/“时候是从当前类所在包路径去获取资源
- class.getResource(“/“)带”/“时候是从classpath的根路径获取
classLoader.getResource
public static void main(String[] args) {
System.out.println(ResourceReader.class.getClassLoader().getResource("/"));
System.out.println(ResourceReader.class.getClassLoader().getResource(""));
System.out.println(ResourceReader.class.getClassLoader().getResource("a.txt"));
System.out.println(ResourceReader.class.getClassLoader().getResource("/test/a.txt"));
System.out.println(ResourceReader.class.getClassLoader().getResource("test/a.txt"));
}
运行结果
null
file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/
file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/a.txt
null
file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/test/a.txt
- getClassLoader().getResource(“”)不带”/“时候是从classpath的根路径获取
- getClassLoader().getResource(“/“)带有”/“打印为null,路径中无法带有”/“
另外class和classloader的类都提供了getResourceAsStream()方法,其仅仅是获取对应路径文件的输入流,在路径的用法上与getResource()一致。
常用读取资源文件的用法
public static List<String> readFromResource(String fileName) throws IOException {
InputStream inputStream = ResourceReader.class.getClassLoader().getResourceAsStream(fileName);
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
return lines;
}
使用apache io工具包
IOUtils.readLines(ResourceReader.class.getClassLoader().getResourceAsStream(fileName))
使用guava包
Resources.readLines(ResourceReader.class.getClassLoader().getResource(fileName), Charset.defaultCharset())