从 classpath 读取文件

下面会讲解一下如何从 classpath 中读取文件。我们会从src/main/resources目录下读取 test.txt 文件。

从普通类出发

从 classpath 读取文件 - 图1
resources 目录在这里是根目录。
读取 classpath 下的 test.txt 文件。

  1. @Test
  2. public void classpathTest2() throws URISyntaxException, IOException {
  3. Stream<String> lines = Files.lines(Paths.get(FindFileTest.class.getResource("/test.txt").toURI()),
  4. StandardCharsets.UTF_8);
  5. List<String> collect = lines.collect(Collectors.toList());
  6. lines.close();
  7. collect.forEach(System.out::println);
  8. }

上面这个例子中,我们使用了当前类的 getResource 方法,并且把绝对路径当做参数传入了方法中。
如果不加路径的第一个字符不是斜杠,表明这是一个相对路径,从当前类出发,寻找其他文件。

从 ClassLoader 实例出发

同样的方法,我们可以用 ClassLoader 实现读取 classpath 下的 test.txt 文件。

  1. @Test
  2. public void classpathTest() throws URISyntaxException, IOException {
  3. Stream<String> lines = Files.lines(Paths.get( ClassLoader
  4. .getSystemResource("test.txt").toURI()),
  5. StandardCharsets.UTF_8);
  6. List<String> collect = lines.collect(Collectors.toList());
  7. lines.close();
  8. collect.forEach(System.out::println);
  9. }

与普通类不同是,从 ClassLoader 中获取到的路径默认是绝对路径,所以不用在路径前面加斜杠。