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

时间:2016-07-20 04:05:30

标签: java text-files overwrite

嘿伙计我需要我的程序才能存储多个输出,但它只是在文本文件中反复覆盖相同的字符串(总数)。我怎么能这样做它会写出多个答案而不是覆盖它?谢谢:))

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();
}

1 个答案:

答案 0 :(得分:0)

您可以将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

的更多信息