当我使用我的removeOrder()方法时,它成功地从列表中获取顺序,然后我必须使用运行此代码的save()方法。我被抛出一个空指针异常,因为当列表中有0项时,该方法不会完成。我需要一些帮助来解决这个问题。我理解为什么我得到空指针异常,printWriter为null,如果列表中没有订单,我的方法不会遍历orderList,因此它转到out.close()并且它不能关闭具有空值。我只是需要帮助找出可能执行if语句的最佳方法,使其按照我想要的方式工作。
private void writeToFile(List<Order> orderList) throws
FlooringMasteryDaoFileException {
//PrintWriter out = null;
LocalDate date;
//if (orderList.size() >= 1)
for (Order dateOrder : orderList) { // iterate over my orderList
and then get the date from each Order, then format that date to a
string.
date = dateOrder.getDate();
String stringDate = formatDate(date);
try {
out = new PrintWriter(new FileWriter("order_" + stringDate
+ ".txt"));
} catch (IOException e) {
throw new FlooringMasteryDaoFileException("Could not save
order data.");
}
for (Order currentOrder : orderList) {
if (currentOrder.getDate().isEqual(date)) {
out.println(currentOrder.getOrderNumber() + DELIMETER
+ currentOrder.getCustomerName() + DELIMETER
+ currentOrder.getTaxRate() + DELIMETER
+ currentOrder.getProduct() + DELIMETER
+ currentOrder.getArea() + DELIMETER
+ currentOrder.getMaterialCost() + DELIMETER
+ currentOrder.getLaborCost() + DELIMETER
+ currentOrder.getTax() + DELIMETER
+ currentOrder.getTotal() + DELIMETER
+ currentOrder.getDate());
}
}
out.flush();
}
out.close();
}