java - 在 Spring Boot 中浏览 uber jar 中嵌入的文件夹的内容

标签 java spring spring-boot

我正在尝试列出位于 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 等...)但没有成功。

非常感谢您的帮助!

最佳答案

尝试使用 Reflections 库 - 了解更多相关信息 here .:

最新版本的 POM:

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

如何使用它的示例:

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

以下代码将打印出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

我已经在 fat/uber JAR 中对此进行了测试。

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

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

关于java - 在 Spring Boot 中浏览 uber jar 中嵌入的文件夹的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60677370/

相关文章:

spring-boot - 创建 com.example.betterreadsDataloader.BetterreadsDataloader1Application 中定义的名称为 'sessionBuilderCustomizer' 的 bean 时出错

java - HttpServletRequest 到达 Java REST API 后可以为 null 吗?

java - 仅将 https 与 spring cloud 微服务实例一起使用

java - 如何从 RestController 将用户名添加到 graphql 上下文/数据获取环境

java - 将 Flux 条目与 previous 和 map 相结合

java - Jackson 在构造函数中使用 @JsonProperty 名称进行序列化

java - 从与类路径不同的位置加载 spring XML

java - 根据自定义设置日期格式

java - 错误 “double cannot be dereferenced”是什么意思?

java - Jersey、Restful Web 服务、拒绝跨域访问