java 使用 ResourceUtils.getFile 从 Heroku 环境中的类路径读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35726500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using ResourceUtils.getFile to read a file from classpath in Heroku environment
提问by jfcorugedo
I'm running a Spring Boot application in Heroku, using Maven to manage the build lifecycle.
我在 Heroku 中运行 Spring Boot 应用程序,使用 Maven 来管理构建生命周期。
During the initialisation phase of my application, I want to read a file packaged into my JAR file.
在我的应用程序的初始化阶段,我想读取一个打包到我的 JAR 文件中的文件。
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:
.
为了设法获取文件的内容,我使用了 Spring 实用程序类ResourceUtils
,并且我使用特殊前缀来表示文件的路径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.
当我在本地机器上执行应用程序时,此代码按预期工作。
But when I push my application to Heroku I'm getting the following error:
但是当我将应用程序推送到 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
I've run a heroku run bash
and I've checked that the file is just where it should be (inside the jar).
我已经运行了 aheroku run bash
并且我已经检查过该文件是否就在它应该在的位置(在 jar 内)。
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
而且,根据错误跟踪,Spring定位文件,因为它将路径从classpath:com/myapp/myFile.test
到jar:file:/app/target/myapp.jar!/com/myapp/myFile.test
回答by codefinger
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).
我怀疑当您在本地运行时,它正在从分解的 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:
在 Heroku 上,它位于 JAR 文件中,这意味着它不是常规文件,必须作为输入流读取,可能如下所示:
ClassLoader cl = this.getClass().getClassLoader();
InputStream inputStream = cl.getResourceAsStream(pathToMyFile);
Then you might use a BufferedReaderto read the lines. But maybe ResourceUtils
has a better method.
然后您可以使用BufferedReader来读取行。但也许ResourceUtils
有更好的方法。
You can probably reproduce the problem locally by running the same command that's in your Profile
.
您可能可以通过运行Profile
.