使用ResourceUtils.getFile在Heroku环境中从类路径读取文件 [英] Using ResourceUtils.getFile to read a file from classpath in Heroku environment

查看:471
本文介绍了使用ResourceUtils.getFile在Heroku环境中从类路径读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Heroku中运行Spring Boot应用程序,使用Maven来管理构建生命周期.

I'm running a Spring Boot application in Heroku, using Maven to manage the build lifecycle.

在应用程序的初始化阶段,我想读取打包到我的JAR文件中的文件.

During the initialisation phase of my application, I want to read a file packaged into my JAR file.

要设法获取文件的内容,我使用的是Spring实用程序类ResourceUtils,我使用特殊的前缀classpath:表示文件的路径.

To manage to get the content of the file I'm using the Spring utility class ResourceUtils, and I'm expressing the path of the file using the special prefix classpath:.

我正在使用的代码如下:

The code I'm using looks like this:

String pathToMyFile = "classpath:com/myapp/myFile.test"
List<String> fileLines = Files.readLines(ResourceUtils.getFile(pathToMyFile), IOConstants.DEFAULT_CHARSET_TYPE);

当我在本地计算机上执行应用程序时,此代码可以按预期工作.

This code works as expected when I execute the application in my local machine.

但是当我将应用程序推送到Heroku时,出现以下错误:

But when I push my application to Heroku I'm getting the following error:

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内).

I've run a heroku run bash and I've checked that the file is just where it should be (inside the jar).

此外,根据错误跟踪,Spring会找到文件,因为它会将路径从classpath:com/myapp/myFile.test转换为jar:file:/app/target/myapp.jar!/com/myapp/myFile.test

Moreover, according to the error trace, Spring locates the file, because it transform the path from classpath:com/myapp/myFile.test to jar:file:/app/target/myapp.jar!/com/myapp/myFile.test

推荐答案

我怀疑当您在本地运行时,它是从爆炸的JAR文件(即作为文件系统上的常规文件)拾取类路径上的文件.

I suspect that when you are running locally, it is picking up the file on the classpath from an exploded JAR file (i.e. as a regular file on the filesystem).

在Heroku上,它位于JAR文件中,这意味着它不是常规文件,必须将其作为输入流读取,如下所示:

On Heroku, it is in the JAR file, which means it is not a regular file, and must be read as an input stream, which might look like this:

ClassLoader cl = this.getClass().getClassLoader();
InputStream inputStream = cl.getResourceAsStream(pathToMyFile);

然后,您可以使用 BufferedReader 阅读各行.但是ResourceUtils也许有更好的方法.

Then you might use a BufferedReader to read the lines. But maybe ResourceUtils has a better method.

您可以通过运行Profile中的相同命令在本地重现该问题.

You can probably reproduce the problem locally by running the same command that's in your Profile.

这篇关于使用ResourceUtils.getFile在Heroku环境中从类路径读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆