部署方式:
部署方式的不同,后台获取图片的路径会出现获取不到的问题
1、war部署:
因为包含项目的所有内容,可以通过相对路径直接获取
String path = Main.class.getClassLoader().getResource("../../image/device.png").getPath();
2、jar部署
jar包
Main.class.getClassLoader().getResource("../../image/device.png").getPath();得到的结果是null,
所以需要通过获取流的方式 getResourceAsStream() 来获取。
InputStream is = null;
String path ;
try {
//解决jar包部署,获取不到默认图片
is = Main.class.getClassLoader().getResourceAsStream("/image/device.png");
byte[] data = null;
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = is.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
path = new String(swapStream.toByteArray());
} catch (Exception e) {
LOGGER.error(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
outInfo.setStatus(EiConstant.STATUS_FAILURE);
outInfo.setMsg("关闭InputStream流失败!");
}
}
}