Spring ResourceArrayPropertyEditor:如何仅筛选文件?
我正在使用spring.ios ResourceArrayPropertyEditor查找与某些模式匹配的所有资源(为了使本例更简单,假设我正在查找foo文件): 我所做的:Spring ResourceArrayPropertyEditor:如何仅筛选文件?,spring,Spring,我正在使用spring.ios ResourceArrayPropertyEditor查找与某些模式匹配的所有资源(为了使本例更简单,假设我正在查找foo文件): 我所做的: ResourceArrayPropertyEditor resolver = new ResourceArrayPropertyEditor(); String[] resourcePattern = new String[]{"classpath*:**/*.foo"}; resolver.setValue(resour
ResourceArrayPropertyEditor resolver = new ResourceArrayPropertyEditor();
String[] resourcePattern = new String[]{"classpath*:**/*.foo"};
resolver.setValue(resourcePattern);
Resource[] resources = (Resource[]) resolver.getValue();
问题:这不仅会找到类路径上的所有“*.foo”文件,还会找到以“foo”结尾的所有包文件夹,例如:“org.mydomain.database.foo”
我不需要这些条目,甚至在尝试处理它们时会出错
如何筛选资源以仅包含文件?(类似于find.-type f
)。文档中,ResourceArrayPropertyEditor
默认情况下使用路径匹配源模式解析器来解析特定资源。从PathMatchingResourcePatternResolver的属性判断,它将选择与指定模式匹配的所有资源,而不检查它是目录还是文件
唯一的选项是,在获取资源列表后,检查isReadable()
资源的属性
Resource[] resources = (Resource[]) resolver.getValue();
for(Resource resource : resources){
if(resource.isReadable()){
//will work only for files
}
}
或者,如果您使用Java 8流:
Resource [] resources = (Resource[]) resolver.getValue();
Resource [] fileResources = Arrays.stream(resources).filter(Resource::isReadable).toArray(Resource[]::new);
此方法比,resource.getFile().isDirectory()
更可取,因为不需要处理IOException
是否确实有名为org.mydomain.database.sql
的包文件夹?我认为它不是有效的包文件夹名称。在我的真实案例中,我正在查找“*.dmn”文件,其中有一个包org.camunda.bpm.dmn“我只是想避免这个问题的细节。我将在示例中将其更改为foo。你能提供一个工作单元测试吗?我尝试了一下,但没有成功,似乎包是”“可读”,也可以使用“!resource.getFile().isDirectory()
有效however@JanGalinski我在文档中找到了它。当我测试时,文件是可读的,但文件夹是不可读的。您可以从编辑器获得另一个资源
,而不是文件系统资源
。就是这样。我扫描了文件系统。URLROURCE没有实现isReadable。父级抽象的方法源代码类将始终返回true。我不得不考虑它。