jfc*_*edo 6 java spring heroku spring-boot
我在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);
Run Code Online (Sandbox Code Playgroud)
当我在本地计算机中执行应用程序时,此代码按预期工作.
但是,当我将我的应用程序推送到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
Run Code Online (Sandbox Code Playgroud)
我运行了一个heroku run bash
,我已经检查过该文件应该在哪里(在jar中).
而且,根据错误跟踪,Spring定位文件,因为它将路径转换classpath:com/myapp/myFile.test
为jar:file:/app/target/myapp.jar!/com/myapp/myFile.test
我怀疑当您在本地运行时,它是从爆炸的JAR文件(即作为文件系统上的常规文件)拾取类路径上的文件。
在Heroku上,它位于JAR文件中,这意味着它不是常规文件,必须将其作为输入流读取,如下所示:
ClassLoader cl = this.getClass().getClassLoader();
InputStream inputStream = cl.getResourceAsStream(pathToMyFile);
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用BufferedReader读取行。但是也许ResourceUtils
有更好的方法。
您可以通过运行中的相同命令在本地重现该问题Profile
。