使用路径加载
String urlImage = ClassLoader.getSystemClassLoader().getResource("image/ha.jpg").getPath();
ClassPathResource classPathResource = new ClassPathResource("image/ha.jpg");
String urlImage = classPathResource.getURL().getPath();
使用流加载
private byte[] getHarPic() throws IOException {
InputStream input = new ClassPathResource("image/ha.jpg").getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
在linux环境下
war包部署,会解压,因此使用路径或者流的方式都是可行的;
jar包部署,是不会解压的,路径是不可行的,流的方式是可行的;因为无法直接读取压缩包中的文件,读取只能通过流的方式读取