小编典典

每次我使用格式化程序在txt中写入内容时,以前的东西写操作都会被删除?如何避免这种情况?

java

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

阅读 263

收藏
2020-11-26

共1个答案

小编典典

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

  1. 完成所有写入后,打开,写入,写入,…,写入并仅关闭文件。

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

2020-11-26