我发现,结合使用ResourceLoader
,ResourcePatternUtils
这是在Spring Boot应用程序中从类路径资源文件夹列出/读取文件的最佳方法:
@RestController
public class ExampleController {
private ResourceLoader resourceLoader;
@Autowired
public ExampleController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
private List<String> getFiles() throws IOException {
Resource[] resources = ResourcePatternUtils
.getResourcePatternResolver(loader)
.getResources("classpath*:elcordelaciutat/*.txt");
return Arrays.stream(resources)
.map(p -> p.getFilename().toUpperCase())
.sorted()
.collect(toList());
}
}
如果要获取所有文件,包括的子文件夹中的文件elcordelaciutat
,则需要包括以下模式classpath*:elcordelaciutat/**
。这将检索子文件夹(包括子文件夹)中的文件。获得所有资源后,请根据.txt
文件扩展名对其进行过滤。这是您需要进行的更改:
private List<String> getFiles() throws IOException {
Resource[] resources = ResourcePatternUtils
.getResourcePatternResolver(loader)
// notice **
.getResources("classpath*:elcordelaciutat/**");
return Arrays.stream(resources)
.filter(p -> p.getFilename().endsWith(".txt"))
.map(p -> {
try {
String path = p.getURI().toString();
String partialPath = path.substring(
path.indexOf("elcordelaciutat"));
return partialPath;
} catch (IOException e) {
e.printStackTrace();
}
return "";
})
.sorted()
.collect(toList());
}
假设您具有以下资源文件夹结构:
+ resources
+ elcordelaciutat
- FileA.txt
- FileB.txt
+ a-dir
- c.txt
+ c-dir
- d.txt
+ b-dir
- b.txt
过滤后,列表将包含以下字符串: