从 classpath 读取文件
下面会讲解一下如何从 classpath 中读取文件。我们会从src/main/resources
目录下读取 test.txt
文件。
从普通类出发
resources 目录在这里是根目录。
读取 classpath 下的 test.txt 文件。
@Test
public void classpathTest2() throws URISyntaxException, IOException {
Stream<String> lines = Files.lines(Paths.get(FindFileTest.class.getResource("/test.txt").toURI()),
StandardCharsets.UTF_8);
List<String> collect = lines.collect(Collectors.toList());
lines.close();
collect.forEach(System.out::println);
}
上面这个例子中,我们使用了当前类的 getResource 方法,并且把绝对路径当做参数传入了方法中。
如果不加路径的第一个字符不是斜杠,表明这是一个相对路径,从当前类出发,寻找其他文件。
从 ClassLoader 实例出发
同样的方法,我们可以用 ClassLoader 实现读取 classpath 下的 test.txt 文件。
@Test
public void classpathTest() throws URISyntaxException, IOException {
Stream<String> lines = Files.lines(Paths.get( ClassLoader
.getSystemResource("test.txt").toURI()),
StandardCharsets.UTF_8);
List<String> collect = lines.collect(Collectors.toList());
lines.close();
collect.forEach(System.out::println);
}
与普通类不同是,从 ClassLoader 中获取到的路径默认是绝对路径,所以不用在路径前面加斜杠。