【问题标题】:Unable to load resource from classpath in Heroku Java app [duplicate]无法从 Heroku Java 应用程序中的类路径加载资源 [重复]
【发布时间】:2018-10-08 15:21:05
【问题描述】:

我在运行时访问资源文件时遇到问题,该文件存储在我的 JAVA 项目的资源文件夹中。

该项目基于 Spring Boot,我在 src/main/resources 下存储了一些 ddl 和 json 配置文件。 该项目已正确部署(通过 Maven)。但是,当我的代码尝试访问其中一个资源文件时,会出现以下异常:

java.nio.file.NoSuchFileException: file:/app/target/app-backend-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/setup_data/app_data_schema.ddl

我可以从日志中看到,就在此异常之前,另一个文件被 Spring 从同一位置正确加载 (文件:/app/target/app-backend-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/setup_data/schema.sql)。

我还使用 heroku CLI(“heroku run bash”)仔细检查了文件确实已部署到我期望的位置: /app/target/classes/setup_data - test_app_data1.json
- test_app_data2.json
- app_data_schema.ddl

这让我相信问题出在我加载文件的方式上,它在我的机器上本地工作,但在部署到 Heroku 时却不行。 这是我用来找出文件完整路径的代码:

public static String getFullPathForResource(Class<?> resourceClass, String resourceName) {
    URL resourceUrl = resourceClass.getResource(resourceName);
    String fullPath = "";
    if (resourceUrl != null) {
        fullPath = resourceUrl.getPath();
    }

    return fullPath;
}

然后我按如下方式加载文件:

String ddlResourceFullPath = getFullPathForResource(getClass(), ddlResource);
Stream<String> lines = Files.lines(Paths.get(ddlResourceFullPath));

getFullPathForResource() 方法的结果确实是: "文件:/app/target/app-backend-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/schema.sql"

根据我的理解,哪个应该与我的资源的正确路径匹配!

您能指导我如何正确加载资源文件吗?

感谢您的帮助!

【问题讨论】:

    标签: java maven heroku classpath


    【解决方案1】:

    Heroku 的支持向我指出了这个问题。

    问题在于我加载文件的方式,而不是我找到资源路径的方式。 具体来说,这一行:

    Stream<String> lines = Files.lines(Paths.get(ddlResourceFullPath));
    

    Files.lines 期望文件位于文件系统上,并且无法打开 Jar 文件中的文件。

    使用java.lang.ClassLoader.getResourceAsStream() 可以解决问题。 (例如:MyClass.class.getResourceAsStream())

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-26
      • 2016-11-19
      • 2011-03-27
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      相关资源
      最近更新 更多