将用户的输入保存到HashMap中并写入文件

时间:2019-04-06 02:50:06

标签: java file hashmap

我的程序应该从用户那里接收订单(地图),并将其保存到Map内的Map中并写入文件中。当用户输入多个订单(地图)时,最后一个订单(而不是全部订单)被写入文件。 我不明白为什么会这样。有人有什么想法吗?

谢谢



    private Map<LocalDate, Map<Integer, OrderDTO>> orders = new HashMap<>();
//user creates orders
public OrderDTO addOrder(OrderDTO order)  { 
    Map<Integer, OrderDTO> currentOrder = new HashMap<>();
    LocalDate ld = order.getLd();
    order.setOrderN(counter++);
    currentOrder.put(order.getOrderN(), order);      
    orders.put(ld, currentOrder); 
    return order;
}

//user selects "save current work"
    public void saveWork(LocalDate ld) { 
        writeOrder(ld);
    }

//writing into a file
   private void writeOrder(LocalDate ld) { 
        String date = ld.format(DateTimeFormatter.ofPattern("MMddyyyy"));
        String fileName = ORDER_FILE + date + ".txt";
        PrintWriter out;
            out = new PrintWriter(new FileWriter(fileName));
        Map<Integer, OrderDTO> myOrders = orders.get(ld);
        if (myOrders == null) {
            return;
        }
        List<OrderDTO> ordersList = new ArrayList<>(myOrders.values());
        for (OrderDTO order : ordersList) {
            out.println(order.getOrderN() + DELIMITER
                    + order.getCustomer() + DELIMITER
                    + order.getState() + DELIMITER
                    + order.getProduct() + DELIMITER
.........
            out.flush();
        }
        out.close();
    }


0 个答案:

没有答案