2017-09-23 73 views
-3

我想寫訂單到文件。例如,如果文件中的訂單和訂單編號爲1,然後當用戶添加另一個訂單並點擊保存時,訂單將保存爲.txt文件,作爲該日期的訂單編號2。但我的fileWriter寫入的文件與訂單編號1相同。請看看我的DaoImpl。謝謝。如何寫入.txt文件,訂單號碼

private void writeOrder(LocalDate date) throws OrderPersistenceException, IOException { 

    PrintWriter out; 
    try { 
     out = new PrintWriter(new FileWriter(getFilePath(date))); 
    } catch (IOException ex) { 
     throw new OrderPersistenceException("file"); 
    } 

    List<Order> orderList = new ArrayList<>(orderMap.values()); 

    for (Order currentOrderList : orderList) { 

     out.print(currentOrderList.getOrderNumber() + DELIMITER 
       + currentOrderList.getCustomerName() + DELIMITER 
       + currentOrderList.getState() + DELIMITER 
       + currentOrderList.getTaxRate() + DELIMITER 
       + currentOrderList.getProductType() + DELIMITER 
       + currentOrderList.getArea() + DELIMITER 
       + currentOrderList.getCostPerSquareFoot() + DELIMITER 
       + currentOrderList.getLaborCostPerSquareFoot() + DELIMITER 
       + currentOrderList.getMeterialCost() + DELIMITER 
       + currentOrderList.getTotalTax() + DELIMITER 
       + currentOrderList.getTotal()); 

     out.flush(); 
    } 

    out.close(); 
} 

public void saveWork(LocalDate date) throws OrderPersistenceException, IOException { 
    writeOrder(date); 

} 

@Override 
public Order addOrder(Order order) throws OrderPersistenceException { 
    long orderNumber = ordernumberIncrease(order); 
    Order newOrder = orderMap.put(orderNumber, order); 

    return newOrder; 

} 

public Long ordernumberIncrease(Order order) { 
    long orderNumber = orderNumInc++; 
    order.setOrderNumber(orderNumber); 
    return orderNumber; 
} 
+1

歡迎來到Stack Overflow!你已經在你的問題中發佈了很多代碼,這使得我們(以及未來的讀者)不清楚問題出在哪裏。請將您的問題代碼減少到10行或更少。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)和[如何調試小程序](https://ericlippert.com/2014/03/05 /如何調試的小程序/)。 –

+0

我減少了它。希望還是不要太多。謝謝 – Rnhep

回答

0

您需要更新writeOrder方法:

在使用通過out.println代替的out.print的循環 - 那麼每個訂單將在新行開始。

+0

WOW謝謝。我沒有看到。我太累了,精疲力盡了我的搜索技巧。問題解決!謝謝 – Rnhep

+0

一個更快的問題,如果你不介意。即時通訊運行到另一個問題,其中printwrite覆蓋程序重新啓動後寫入現有文件,而不是繼續寫入下一行。應該在writeOrder方法中有IF語句嗎?謝謝 – Rnhep