问题描述
Java application 经过docker build之后,得到app.jar。
使用绝对路径访问文件001.jpg时会报错。
{
"code": "500",
"message": "class path resource [001.jpg] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app/app.jar!/BOOT-INF/classes!/001.jpg",
"data": "class path resource [001.jpg] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app/app.jar!/BOOT-INF/classes!/001.jpg"
}
原因分析
在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流。
解决方案
public class BaiduOCRController {
...
InputStream resourceAsStream = BaiduOCRController.class.getResourceAsStream("/001.jpg");
FastByteArrayOutputStream read = IoUtil.read(resourceAsStream);
byte[] data = read.toByteArray();
...
}
BaiduOCRController 与 001.jpg在相同目录。
Class.class.getResourceAsStream 的默认路径
默认情况下,资源路径是相对于该类所在的包路径。
com.example.MyClass
MyClass.class.getResourceAsStream("data.txt"),该方法会在与MyClass类相同的包路径下查找名为data.txt的资源文件。
MyClass.class.getResourceAsStream("/data.txt")将会在类路径的根目录下查找名为data.txt的资源文件。