【发布时间】:2016-06-14 01:59:18
【问题描述】:
我在 Heroku 中运行 Spring Boot 应用程序,使用 Maven 管理构建生命周期。
在我的应用程序的初始化阶段,我想读取一个打包到我的 JAR 文件中的文件。
为了设法获取文件的内容,我使用 Spring 实用程序类 ResourceUtils,并使用特殊前缀 classpath: 表示文件的路径。
我使用的代码如下所示:
String pathToMyFile = "classpath:com/myapp/myFile.test"
List<String> fileLines = Files.readLines(ResourceUtils.getFile(pathToMyFile), IOConstants.DEFAULT_CHARSET_TYPE);
当我在本地机器上执行应用程序时,此代码按预期工作。
但是当我将应用程序推送到 Heroku 时,我收到以下错误:
Caused by: java.io.FileNotFoundException: class path resource [com/myapp/myFile.test]
cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/app/target/myapp.jar!/com/myapp/myFile.test
我运行了heroku run bash 并检查了文件是否就在它应该在的位置(在 jar 内)。
此外,根据错误跟踪,Spring 定位文件,因为它将路径从classpath:com/myapp/myFile.test 转换为jar:file:/app/target/myapp.jar!/com/myapp/myFile.test
【问题讨论】:
-
您不能将其作为文件读取,您必须像在
InputStream中那样读取它。File必须是系统上的实际资源(使用它进行读取或写入时)。这也是错误告诉你的。 -
是的,你是对的。我最终使用了
ResourceUtils.getURL().openStream() -
您可能想使用 Guava 的 Resources.toString(Resources.getResource(pathToMyFile), Charset.forName("UTF-8")) 从您的应用程序 jar 中读取文件。
标签: java spring heroku spring-boot