覆盖文本文件中的输出(需要保存所有输出)

Overwriting output in textfile (need to save all outputs)

大家好,我需要我的程序能够存储多个输出,但它只是在文本文件中一遍又一遍地覆盖相同的字符串(总计)。我怎样才能让它写出多个答案而不是覆盖它?谢谢:)

static int boys;
static int girls;
static int total;

public static void program() {



     System.out.println("enter number of girls: ");
     girls = input.nextInt();
     System.out.println("enter number of boys: ");
     boys = input.nextInt();
     total = boys+girls;

     System.out.println(total);


}

private static Formatter x;

public void openFile () {
    try {
        x = new Formatter("income.txt");
    }

    catch(Exception e) {
        System.out.println("You have an error");
    }
}

public static void addRecords(){
    x.format("%s%s%s", " 19", " James", " A");
    x.format("%s%s", "\n", total);



}

public void closeFile(){
    x.close();
}

您可以将 openFile 方法更改为如下内容:

public void openFile(){
    try {
        Appendable appendable = new FileWriter("income.txt",true);
        x = new Formatter(appendable);
    } catch(Exception e) {
        System.out.println("You have an error");
    }
}

重要的部分是 new FileWriter("income.txt",true);,这会创建一个新的 FileWriter,将数据附加到 income.txt 文件。

您可以找到更多相关信息HERE