每次我使用格式化程序在txt中写入以前的东西都会被删除吗?怎么能避免这种情况?

import java.io.FileNotFoundException; import java.lang.SecurityException; import java.util.Formatter; import java.util.FormatterClosedException; import java.util.NoSuchElementException; import javax.swing.JOptionPane; public class CreateTextFile { private Formatter output; //object used to output text to file private Order order; //enable user to open file public void openFile() { try { output=new Formatter("src\\Orders.txt");//pen the file }//end try catch(SecurityException securityException) { JOptionPane.showMessageDialog(null,"You do not have the write access to this file.","Error", JOptionPane.ERROR_MESSAGE); System.exit(1);//terminate the program }//end catch catch(FileNotFoundException filenotfoundexception) { JOptionPane.showMessageDialog(null,"Error opening or creating file.","Error", JOptionPane.ERROR_MESSAGE); System.exit(1);//terminate the program }//end catch }//end method openFile //add records to file public void addOrderstoSalesmen(String Description,String Date, double poso,int salesman,Employee currentEmployee) { try //output values to file { //retrieve data to be ouput order=new Order(Description,Date,poso,salesman); Salesman employee=(Salesman) currentEmployee; employee.addOrder(order); employee.setGrossSales(salesman); output.format("%s,%s,%.0f\n",order.getDescription(),order.getDate(),order.getSales()); }//end try catch(FormatterClosedException formatterclosedexception) { JOptionPane.showMessageDialog(null,"Error writing to file.","Error", JOptionPane.ERROR_MESSAGE); return; }//end catch catch(NoSuchElementException elementexception) { JOptionPane.showMessageDialog(null,"Invalid input.Please try again.","Error", JOptionPane.ERROR_MESSAGE); }//end catch }//end method addRecords public void CloseFile() { if(output!=null) output.close(); }//end method closeFile }//end class CreateTextFile 

您可能正在打开,写入,关闭文件然后重复。 每次打开文件进行写入时,其内容都会被清除干净。 您可以通过以下方式解决这个问题:

  1. 打开,写作,写作,…,写作,只有在完成所有写作后才关闭文件。

  2. 以附加模式打开文件,因此不会删除旧内容。

使用Formatter 在重新打开现有文件时删除文件内容,如构造函数所记录的那样

…如果文件存在,那么它将被截断为零大小; …

使用带有FileWritter的BufferedWritter( append = true )来构造Formatter:

  new Formatter(new BufferedWriter(new FileWriter("src/Orders.txt", true))); 

注意:让程序写入源目录有点奇怪