[英]How to read, write content to text file using FileWriter and BufferedWriter in Java
[英]How to write detail into file using BufferedWriter and FileWriter in Java?
我在文件中写入这些详细信息时遇到问题。 我试图在文件中写入此详细信息,但是一些此函数如何在特定位置创建文件,但未将任何内容写入文件。
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){}
}
}
尝试致电
bw.flush();
关闭文件之前。 优良作法是每次您写入大量数据时刷新流。 在您的情况下,将此调用添加到2个位置:在while循环主体的末尾和bw.write("Thank You...!")
。
代码中的错误是您在关闭BufferedWriter实例之前已关闭FileWriter实例。 如果您只是交换bw.close()和fw.close()的位置,它将起作用。 您的finally块应如下所示:
finally
{
try
{
bw.close();
fw.close();
}
catch(Exception e)
{}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.