格式化程序 class 每次写入文本文件后都不会保留数据

Formatter class doesn't keep data after each time writing on the text file

我正在开发一个在文本文件上写入的应用程序。应用程序正确地将数据写入文件,但是如果我重新启动应用程序并写入新输入,它会将新输入替换为我写在文件上的旧输入,但我需要的是保留我之前写入的旧输入新的

public class IoWrite
{
    private static Formatter output; // outputs text to a file

    public static void main(String[] args)
    {
        openFile();
        addRecords();
        closeFile();
    }

    // open file clients.txt
    public static void openFile()
    {
        try
        {
            output = new Formatter("clients.txt"); // open the file
        }
        catch (SecurityException securityException)
        {
            System.err.println("Write permission denied. Terminating.");
            System.exit(1); // terminate the program
        }
        catch (FileNotFoundException fileNotFoundException)
        {
            System.err.println("Error opening file. Terminating.");
            System.exit(1); // terminate the program
        }
    }

    // add records to file
    public static void addRecords()
    {
        Scanner input = new Scanner(System.in);
        System.out.printf("%s%n%s%n? ",
                "Enter account number, first name, last name and balance.",
                "Enter end-of-file indicator to end input.");

        while (input.hasNext()) // loop until end-of-file indicator
        {
            try
            {
                // output new record to file; assumes valid input
                output.format("%d %s %s %.2f%n", input.nextInt(),
                        input.next(), input.next(), input.nextDouble());
            }
            catch (FormatterClosedException formatterClosedException)
            {
                System.err.println("Error writing to file. Terminating.");
                break;
            }
            catch (NoSuchElementException elementException)
            {
                System.err.println("Invalid input. Please try again.");
                input.nextLine(); // discard input so user can try again
            }

            System.out.print("?");
        }
    }

    // close file
    public static void closeFile()
    {
        if (output != null)
            output.close();
    }
} // end class CreateTextFile

您可以使用 FileWriter 附加到现有文件。

openFile 方法更新为,

// open file clients.txt
public static void openFile()
{
    try
    {
        FileWriter fileWriter = new FileWriter("clients.txt", true);
        output = new Formatter(fileWriter); // open the file
    }
    catch (SecurityException securityException)
    {
        System.err.println("Write permission denied. Terminating.");
        System.exit(1); // terminate the program
    }
    catch (FileNotFoundException fileNotFoundException)
    {
        System.err.println("Error opening file. Terminating.");
        System.exit(1); // terminate the program
    }
}

注意 - 在 FileWriter 构造函数中,我将 append 标志保留为 true