2012-03-06 68 views
0

我有一個問題,在文件中寫入這些細節。 我想寫在文件中的這個細節,但一些如何這個功能創建文件在特定的位置,但它不寫入任何文件。如何在Java中使用BufferedWriter和FileWriter將詳細信息寫入文件?

public void writeBillToFile(double amount , double billingAmount,double taxAmount, 
            double discount ,double transactionID , double billingNumber , 
            int customerID , String tableNumber ,ArrayList listObject ) 
    { 
     FileWriter fw=null ; 
     BufferedWriter bw =null; 
     Date d=new Date();   
     long currentTimestamp=d.getTime(); 
     try{ 

      fw = new FileWriter("D:/study/ADVANCE_JAVA/PrOgRaMs/WEB_APPS/00_COS-THE MEGA PROJECT/COS_March_03/GeneratedBill/bill"+currentTimestamp+".txt" , true);   
      bw= new BufferedWriter(fw); 

      System.out.println("Date and Time :: "+d.toString() +"\t Bill No :: "+billingNumber+"\t Transaction ID :: "+transactionID+"\n"); 
      bw.write("Date and Time :: "+d.toString() +" Bill No::"+billingNumber+" Transaction ID::"+transactionID); 
      bw.newLine(); 
      Iterator iteratorObject= listObject.iterator(); 
      while(iteratorObject.hasNext())   
      {   
       ItemInSessionModel itemObject = (ItemInSessionModel)iteratorObject.next(); 
       bw.write(itemObject.getItemName()+" "+itemObject.getItemQty()+"  "+itemObject.getItemRate()+"  "+(itemObject.getItemRate()*itemObject.getItemQty())); 
       bw.newLine(); 
      } 

      bw.write("Total Amount ::"+amount); 
      bw.newLine(); 
      bw.write("Discount  ::"+discount); 
      bw.newLine(); 
      bw.write("TAX   ::"+taxAmount); 
      bw.newLine(); 
      bw.write("Bill Amount ::"+billingAmount); 
      bw.newLine(); 
      bw.write("Thank You...!"); 
      System.out.println("Successfully Writen in File...!"); 
     }catch(Exception e) 
     { 
      System.out.println("Exception in FILE IO :: "+e); 
     } 
     finally 
     { 
      try{ 
      fw.close(); 
      bw.close(); 
      }catch(Exception e){} 
     } 
    } 

回答

0

代碼中的錯誤是,在關閉BufferedWriter的實例之前,您已經關閉了FileWriter的實例。它會工作,如果你只是交換位置的bw.close()和fw.close(); 您的finally塊應如下所示:

finally 
{ 
    try 
    { 
     bw.close(); 
     fw.close(); 
    } 
    catch(Exception e) 
    {} 
} 
+0

您能幫我編寫打印相同文件的代碼嗎? 我已經通過了Oracle的2DPrinting教程,但我想打印我生成的相同的txt文件。所以你能幫我解釋一下嗎? – CyberWorm 2012-03-06 20:48:18

0

嘗試關閉文件之前調用

bw.flush();

。好的做法是每次寫入重要的數據時刷新數據流。在你的情況下,將這個調用添加到2個地方:在while循環體的末尾和bw.write("Thank You...!")之後。

相關問題