如何使用格式化程序附加到 java 中的文件?

How to append to a file in java using formatter?

我有一个简单的问题。我使用此代码使用 java 在文本文件中添加一些记录,但每次我 运行 此程序时,都会再次创建该文件。我想在不重新创建文件的情况下追加记录?

   Formatter x = null;


    try{

    x = new Formatter("C:\Users\Hamada\Downloads\products.txt");

    }

    catch(Exception e)

    {

    //System.out.println("NO Database");

    }

    x.format("%d,%s,%s,%s,%d,%d,%d,%d,%d,%d,%d",id, name, type, brand, quantity, day1, month1, year1, day2, month2, year2);

    x.close();

您需要向 Formatter 添加一个 FileStream,如下所示,并将 appendable 写入 Formatter。

FileWriter f = new FileWriter("C:\Users\Hamada\Downloads\products.txt", true);
Formatter form = new Formatter(f);

在 FileWriter 中传递 "true" 参数以附加到文件而不覆盖当前内容。