代码之家  ›  专栏  ›  技术社区  ›  eftshift0

springboot:如果从jar运行,资源文件不可访问的原因是什么?

  •  0
  • eftshift0  · 技术社区  · 4 年前

    我正在开发一个springboot应用程序。我需要加载一个在参考资料中的文件。如果我运行单元测试(maven,以防万一),那么可以毫无问题地加载该文件。。。甚至是集成测试。但当我运行应用程序时, 真的吗 ,然后就找不到了。我尝试了几种不同的方法来实现它,但都失败了:

    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 从罐子 ,代码非常简单:

        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;
    

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

    1 回复  |  直到 4 年前
        1
  •  1
  •   HÆ°ng Chu    4 年前

    也许这能回答你的问题: Cannot read file within jar file