Spring Boot 中解决 ClassPathResource 获取文件路径报错: java.io.FileNotFoundException
Spring Boot 中解决 ClassPathResource 获取文件路径报错: java.io.FileNotFoundException
在 Spring Boot 项目中,当尝试使用 ClassPathResource 获取资源文件路径并通过 getFile() 方法获取文件时,可能会遇到 java.io.FileNotFoundException 错误,错误信息类似于:
java.io.FileNotFoundException: class path resource [font/msyh.ttf] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/data/reformer-saas-business/reformer-saas-business-svc-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/font/msyh.ttf
问题原因:
这是因为在 Spring Boot 中,资源文件会被打包在 Jar 包中,而不是以文件系统的形式存在,所以无法直接通过 getFile() 方法获取文件的绝对路径。
解决方法:
可以使用 ClassPathResource 的输入流获取文件内容,然后再将文件内容传递给 BaseFont.createFont() 方法。
示例代码:
ClassPathResource fronTtf = new ClassPathResource('font/msyh.ttf');
InputStream inputStream = fronTtf.getInputStream();
BaseFont baseFont = BaseFont.createFont('msyh.ttf', BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, true, inputStream, null);
参数解释:
- 第一个参数是字体文件的名称。
- 第二个参数是编码格式,这里设置为
BaseFont.IDENTITY_H。 - 第三个参数设置为
BaseFont.NOT_EMBEDDED,表示不嵌入字体文件。 - 第四个参数设置为
true,表示使用缓存。 - 第五个参数是字体文件的输入流。
- 第六个参数是字体文件的字节码,可以传递
null。
通过这种方式,就可以在 Spring Boot 项目中正确地使用 ClassPathResource 获取资源文件并进行操作。
原文地址: https://www.cveoy.top/t/topic/nErD 著作权归作者所有。请勿转载和采集!