Spring Boot uber JAR:无法解析为绝对文件路径,因为它不驻留在文件系统中

Sal*_*twa 6 java spring-boot

将 Spring Boot 版本 1.5.7.RELEASE 导出到可运行 JAR 后出现以下错误。出于安全原因,我不使用 Maven,并且我在构建路径中添加了所有 JAR。

我运行下面的命令

java -jar mailer.jar
Run Code Online (Sandbox Code Playgroud)

然后我收到错误,如屏幕截图所示

在此输入图像描述

nhu*_*uvy 8

因为当你的资源不存在于打包的 uber-jar 中时,类路径就会出现问题。使用这样的解决方案

String fuu = "";
ClassPathResource classPathResource = new ClassPathResource("static/foo.txt");
try {
    byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
    fuu = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)


Zia*_*nur 5

尝试这个

IOUtils.toString(new InputStreamReader(this.getClassLoader().getResourceAsStream("fileName.json")))

OR

new InputStreamReader(new ClassPathResource("fileName.json", this.getClassLoader()).getInputStream())
Run Code Online (Sandbox Code Playgroud)

不要使用FileReaderFile

使用InputStreamReaderInputStream