springboot项目读取 resources 目录下的文件的9种方式(总结)
在Spring Boot项目中,读取resources目录下的文件可以通过多种方式实现。以下是几种常见的方法:
- 使用
ResourceLoader
读取文件:
@Autowired
private ResourceLoader resourceLoader;
public void readFile() throws IOException {
Resource resource = resourceLoader.getResource("classpath:filename.txt");
String content = new String(Files.readAllBytes(Paths.get(resource.getURI())));
System.out.println(content);
}
- 使用
ClassPathResource
读取文件:
public void readFile() throws IOException {
ClassPathResource classPathResource = new ClassPathResource("filename.txt");
String content = new String(Files.readAllBytes(classPathResource.getFile().toPath()));
System.out.println(content);
}
- 使用
InputStream
读取文件:
public void readFile() throws IOException {
try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("filename.txt")) {
String content = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(content);
}
}
- 使用Spring的
ResourceUtils
工具类:
public void readFile() throws IOException {
Resource resource = ResourceUtils.getResource("classpath:filename.txt");
String content = new String(Files.readAllBytes(Paths.get(resource.getURI())));
System.out.println(content);
}
- 使用
PathMatchingResourcePatternResolver
读取文件:
public void readFile() throws IOException {
Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:filename.txt");
String content = new String(Files.readAllBytes(Paths.get(resources[0].getURI())));
System.out.println(content);
}
- 使用Spring的
ApplicationContext
读取文件:
@Autowired
private
评论已关闭