如何列出web模块中classpath内目录中的文件

问题描述 投票:2回答:2

在我的WEB应用程序中,有一个带有JSON和文本文件的类路径或资源目录。

/classes/mydir/a.json  
/classes/mydir/b.json
/classes/mydir/b.txt
/classes/mydir/xyz.json

我需要一个InputStream(给杰克逊JSON ObjectMapper)到这个目录中的所有JSON文件。

我做了

URL dirUrl = getClass().getResource("/mydir");

这给了我

vfs:/content/mywar.war/WEB-INF/classes/mydir/

哪个是正确的目录,但使用toUri,File或nio类的任何下一步都抱怨不支持'vfs'。

是否有任何(JBoss / EAP)实用程序类从JBoss EAP中的类路径中读取资源,或者有人可以给出一个示例来执行类路径目录的JSON文件列表?希望不要使用另一个依赖项。

运行时:JBoss EAP 7.1.4.GA(WildFly Core 3.0.17.Final-redhat-1) Java:1.8.0_191-b12

java jboss-eap-7 vfs
2个回答
1
投票

@Karol的答案终于让我找到了我正在寻找的RedHat jboss-vfs框架。所以我在我的pom中加入了以下maven artefact

    <dependency>
        <groupId>org.jboss</groupId>
        <artifactId>jboss-vfs</artifactId>
    </dependency>

然后我做以下事情:

URL dirUrl = getClass().getResource("/mydir");
VirtualFile vfDir = VFS.getChild(dirUrl.toURI());
List<VirtualFile> jsonVFs = vfDir.getChildren(new VirtualFileFilter() {
    @Override
    public boolean accepts(VirtualFile file) {
        return file.getName().toLowerCase().endsWith(".json");
    }
});
for (int i = 0; i < jsonVFs.size(); i++) {
    VirtualFile vf = jsonVFs.get(i);
    File f = vf.getPhysicalFile();
    MyClass fromJson = objectMapper.readValue(f, MyClass.class); 
    // Do something with it..
}

正是我需要的。


0
投票

您可以使用Reflections库扫描类路径上的包:

Reflections reflections = new Reflections("mydir", new ResourcesScanner());
Set<String> resources = reflections.getResources(Pattern.compile(".*"));
System.out.println(resources); // [mydir/a.json, ...
© www.soinside.com 2019 - 2024. All rights reserved.