spring boot 项目打成的 jar 包无法获取 srcmainresources 下文件

spring boot 项目打成的 jar 包无法获取 src/main/resources 下文件

java.io.FileNotFoundException: class path resource [orgs.json] cannot be resolved to absolute file path because it does not reside in the file system

resource.getFile() expects the resource itself to be available on the file system, i.e. it can’t be nested inside a jar file. This is why it works when you run your application in STS but doesn’t work once you’ve built your application and run it from the executable jar. Rather than using getFile() to access the resource’s contents, I’d recommend using getInputStream() instead. That’ll allow you to read the resource’s content regardless of where it’s located.

resource.getFile() 资源本身在文件系统上可用,即它不能嵌套在jar文件中。这就是为什么当您在STS中运行应用程序时,它可以工作,但一旦您构建了应用程序并从可执行jar运行它,它就不能工作。我建议使用getInputStream()而不是使用getFile()来访问资源的内容。这将可以使您能够读取到资源的内容,而不管它位于何处。

解决方式一:

String data = "";
ClassPathResource cpr = new ClassPathResource("static/file.txt");
try {
    byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
    data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
    e.printStackTrace();
}

你可能感兴趣的:(后端,spring,boot,jar,java)