class.getResource

class.getResource
测试用例

  1. public static void main(String[] args) {
  2. System.out.println(ResourceReader.class.getResource(""));
  3. System.out.println(ResourceReader.class.getResource("/"));
  4. System.out.println(ResourceReader.class.getResource("a.txt"));
  5. System.out.println(ResourceReader.class.getResource("/test/a.txt"));
  6. }

resource目录
image.png
输出

  1. file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/utils/
  2. file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/
  3. null
  4. file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/a.txt
  5. file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/test/a.txt
  1. class.getResource(“”) 不带”/“时候是从当前类所在包路径去获取资源
  2. class.getResource(“/“)带”/“时候是从classpath的根路径获取

classLoader.getResource

  1. public static void main(String[] args) {
  2. System.out.println(ResourceReader.class.getClassLoader().getResource("/"));
  3. System.out.println(ResourceReader.class.getClassLoader().getResource(""));
  4. System.out.println(ResourceReader.class.getClassLoader().getResource("a.txt"));
  5. System.out.println(ResourceReader.class.getClassLoader().getResource("/test/a.txt"));
  6. System.out.println(ResourceReader.class.getClassLoader().getResource("test/a.txt"));
  7. }

运行结果

  1. null
  2. file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/
  3. file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/a.txt
  4. null
  5. file:/Users/aitozi/ant/work/code/personal/algorithm-training/target/classes/test/a.txt
  1. getClassLoader().getResource(“”)不带”/“时候是从classpath的根路径获取
  2. getClassLoader().getResource(“/“)带有”/“打印为null,路径中无法带有”/“

另外class和classloader的类都提供了getResourceAsStream()方法,其仅仅是获取对应路径文件的输入流,在路径的用法上与getResource()一致。

常用读取资源文件的用法

  1. public static List<String> readFromResource(String fileName) throws IOException {
  2. InputStream inputStream = ResourceReader.class.getClassLoader().getResourceAsStream(fileName);
  3. List<String> lines = new ArrayList<>();
  4. try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
  5. String line = null;
  6. while ((line = reader.readLine()) != null) {
  7. lines.add(line);
  8. }
  9. }
  10. return lines;
  11. }

使用apache io工具包

  1. IOUtils.readLines(ResourceReader.class.getClassLoader().getResourceAsStream(fileName))

使用guava包

  1. Resources.readLines(ResourceReader.class.getClassLoader().getResource(fileName), Charset.defaultCharset())