Spring 引导:如果从 jar 运行 无法访问资源文件的原因是什么?

Spring Boot: what would be the reasons for a resource file not to be reachable if running from a jar?

我正在开发一个 springboot 应用程序。我需要加载资源中的文件。如果我 运行 单元测试(maven,以防万一)......甚至集成测试,则可以毫无问题地加载文件。但是当我 运行 应用程序说 for real,从打包的 jar 中,然后找不到它。我尝试了几种不同的方法来达到它,但都失败了:

java.lang.IllegalArgumentException: resource path-to-file not found.
        at com.google.common.base.Preconditions.checkArgument(Preconditions.java:217) ~[grpc-1.23.jar!/:?]
        at com.google.common.io.Resources.getResource(Resources.java:195) ~[grpc-1.23.jar!/:?]

另一种方式:

java.io.FileNotFoundException: class path resource [path-to-file] cannot be resolved to absolute file path because it does not exist
        at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:177) ~[spring-core-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]

文件在 WEB-INFO/classes/path-to-file 中,它来自我项目中的 src/main/resources/path-to-file

感谢任何开箱即用的想法。

更新 1 这使得它可以从 jar 运行,并且代码非常简单:

    ClassPathResource cl = new ClassPathResource(resourcePath);
    URL url = cl.getURL();
    String content;
    try (InputStream in = url.openStream()) {
      content = new String(in.readAllBytes(), StandardCharsets.UTF_8);
    }
    LOG.info("Content from {} is {} bytes long", resourcePath, content.length());
    return content;

提示来自标记为已接受的答案。谢谢!

也许这会回答您的问题:

根据我的经验,要处理 jar 中的资源,我会改用 InputStream