SpringBoot项目里要读取项目中的文件内容,本地运行时正常,打包部署读取文件时报错
cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/xxxx-1.0.0-SNAPSHOT.jar!/BOOT-INF/classes!/data/123.txt
报错代码:
File file = ResourceUtils.getFile("classpath:data/123.txt");
String fileContent = FileUtil.readString(file, StandardCharsets.UTF_8);
报错原因:
打包后,项目将从jar包中,而不是从文件系统中读取文件。
解决方式:
从jar中读取文件流
ClassPathResource resource = new ClassPathResource("data/123.txt");
InputStream inputStream = resource.getInputStream();
String fileContent = IOUtils.toString(inputStream, "utf-8");
完结撒花✿✿ヽ(°▽°)ノ✿