我正在尝试读取 Spring Boot 控制台应用程序的资源文件夹中的文件,但出现文件未找到异常。
这是我的 pom
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
Run Code Online (Sandbox Code Playgroud)
这是例外:
java.io.FileNotFoundException: class path resource [9.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/abc/Documents/workspace-sts-3.8.4.RELEASE/xyz/target/xyz-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/9.txt
Run Code Online (Sandbox Code Playgroud)
我打开了 xyz-0.0.1-SNAPSHOT.jar 文件,9.txt 位于 BOOT-INF/classes 文件夹中。
谢谢,-dj
这是 Spring Boot,让我们使用 ClassPathResource
@Component
public class MyBean {
@Value("9.txt")
private ClassPathResource resource;
@PostConstruct
public void init() throws IOException {
Files.lines(resource.getFile().toPath(), StandardCharsets.UTF_8)
.forEach(System.out::println);
}
}
Run Code Online (Sandbox Code Playgroud)
更新:由于ClassPathResource支持解析为 java.io.File 如果类路径资源驻留在文件系统中,但不支持 JAR 中的资源,因此最好使用这种方式
@Component
public class MyBean {
@Value("9.txt")
private ClassPathResource resource;
@PostConstruct
public void init() throws IOException {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
bufferedReader.lines()
.forEach(System.out::println);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6128 次 |
| 最近记录: |