下面是重写后的代码:
public BatchDataVO<OrdersDetail> importNotDelivered(User user, InputStream fileIn) throws Exception {
BatchDataVO<OrdersDetailTO> batchDataVO = ordersDetailImportService.parseExcelNotDelivered(user, fileIn);
List<OrdersDetailTO> importData = batchDataVO.getSuccesses();
List<OrdersDetailTO> errors = batchDataVO.getErrors();
int sum = importData.size() + errors.size();
List<OrdersDetail> success = new ArrayList<>();
StringBuilder errorMessage = new StringBuilder();
BatchDataVO<OrdersDetail> detailBatchDataVO = new BatchDataVO<>();
List<OrdersDetailTO> uniqueList = this.getUniqKey(user, importData, errors);
if (CollectionUtils.isEmpty(importData)) {
detailBatchDataVO.setMessage(String.format("共导入[%s]条数据,成功[0]条,失败[%s]条!", success.size() + errors.size(), errors.size()));
OrdersDetails ordersDetails = this.parseErrors(user, errors);
detailBatchDataVO.setErrors(ordersDetails);
return detailBatchDataVO;
}
for (OrdersDetailTO ordersDetailTO : uniqueList) {
try {
this.importNotDeliverData(user, ordersDetailTO, success);
} catch (Exception e) {
ordersDetailTO.setErrorMessage(e.getMessage());
errors.add(ordersDetailTO);
}
}
detailBatchDataVO.setSuccesses(success);
OrdersDetails ordersDetails = this.parseErrors(user, errors);
detailBatchDataVO.setErrors(ordersDetails);
if (CollectionUtils.isNotEmpty(detailBatchDataVO.getErrors())) {
int index = 0;
for (OrdersDetail ordersDetail : detailBatchDataVO.getErrors()) {
index++;
errorMessage.append("失败原因").append(index).append(": ").append(ordersDetail.getErrorMessage()).append("\n");
}
}
int error = CollectionUtils.isEmpty(detailBatchDataVO.getErrors()) ? 0 : detailBatchDataVO.getErrors().size();
detailBatchDataVO.setMessage(String.format("共导入[%s]条数据,成功[%s]条,失败[%s]条!", sum , sum - error, error));
return detailBatchDataVO;
}
我对代码进行了以下修改:
- 将
StringBuffer改为StringBuilder,因为StringBuilder是线程不安全的,在单线程情况下性能更好。 - 修改字符串格式化语法,使用占位符
%s替代原来的+连接字符串方式。 - 修改注释中的错误拼写(成功 -> 失败)。
- 根据 Java 命名规范,将变量名
detailbatchdatavo改为detailBatchDataVO。
请注意,重写的代码仅做参考,请根据实际需求进行适当修改和调整。
内容由零声教学AI助手提供,问题来源于学员提问




