首页 > 解决方案 > 在 SpringBoot 中浏览嵌入在 uberjar 中的文件夹的内容

问题描述

我正在尝试列出位于我的 SpringBoot 应用程序的 /src/main/resource/ 文件夹中的文件夹的内容。该文件夹包含常规文件。该代码在 IDE (STS) 中运行良好,但在打包应用程序后就不行了。

这是代码:

    Resource xCatRawResource = resourceLoader.getResource(xCatRawResourcePath);

    try(
            InputStream in = xCatRawResource.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in))
    ) 
    {               
            byte[] bdata = FileCopyUtils.copyToByteArray(in);
            String data = new String(bdata, StandardCharsets.UTF_8);
            // data is an empty String when app is packaged

    }
    catch(IOException ioe) {
        LOGGER.error("Unable to parse XCAT names", ioe);
    }

我尝试了不同的策略(使用 ResourceUtils 等),但没有成功。

非常感谢您的帮助!

标签: javaspringspring-boot

解决方案


尝试使用 Reflections 库 -在此处阅读更多相关信息。:

最新版本的 POM:

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.12</version>
</dependency>

如何使用它的一个例子:

假设您的目录中有一个名为jsonfiles/src/main/resource/目录。

以下代码将打印出jsonfiles目录的内容:

import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.ClasspathHelper;
import java.util.regex.Pattern;
import java.util.Set;

...

Reflections reflections = new Reflections(new ConfigurationBuilder()
        .setUrls(ClasspathHelper.forPackage("YOUR.PACKAGE.NAME.HERE"))
        .setScanners(new ResourcesScanner()));
Set<String> resources = reflections.getResources(Pattern.compile("jsonfiles.*"));
resources.forEach((resource) -> {
    System.out.println(resource);
});

输出将是这样的:

jsonfiles/json_file_one.json
jsonfiles/json_file_two.json

我已经在胖/超级 JAR 中对此进行了测试。

免责声明:我不使用 Spring - 所以如果这以某种方式导致您的问题,那么我的解决方案可能不起作用。但我希望它会。

(一个小点:我注意到,在你的问题中,你的代码定义了一个br你不使用的缓冲阅读器 - 你使用输入流in。)


推荐阅读