1.删除
(格式如123.png;123.png;123.png)
Road road = roadService.selectById(Long.valueOf(id));
String[] split1 = road.getImgurl().split(";");
for (String s1 : split1) {
File file = new File(url + s1);
if (file.exists()) {
file.delete();
}
}
2.更新
1.多个(格式如123.png;123.png;123.png)
//是否删除图片
String[] oldImgUrlList = roadService.selectById(road.getId()).getImgurl().split(";");//获取数据库里面的图片地址
String[] imgUrlList = road.getImgurl().split(";");//获取传过来的图片地址
String[] result_minus = StringManageUtil.minus(oldImgUrlList, imgUrlList);
for (String imgUrl : result_minus) {//新旧路径差集,删除不存在于数据里的图片地址
if (StringUtils.isNotBlank(imgUrl)) {
File file = new File(url + imgUrl);
if (file.exists()) {
file.delete();
}
}
}
取差集工具类
//求两个数组的差集
public static String[] minus(String[] arr1, String[] arr2) {
LinkedList<String> list = new LinkedList<String>();
LinkedList<String> history = new LinkedList<String>();
String[] longerArr = arr1;
String[] shorterArr = arr2;
//找出较长的数组来减较短的数组
if (arr1.length > arr2.length) {
longerArr = arr2;
shorterArr = arr1;
}
for (String str : longerArr) {
if (!list.contains(str)) {
list.add(str);
}
}
for (String str : shorterArr) {
if (list.contains(str)) {
history.add(str);
list.remove(str);
} else {
if (!history.contains(str)) {
list.add(str);
}
}
}
String[] result = {};
return list.toArray(result);
}
2.单个
//老图
String imgurl = bussupervisionStationService.select(bussupervisionStation.getId()).getImgurl();
//新图
String imgurl1 = bussupervisionStation.getImgurl();
//不一样则删除老图
if (imgurl!=null){
if (!Objects.equals(imgurl,imgurl1)){
File file = new File(url + imgurl);
if (file.exists()) {
file.delete();
}
}}
|