【问题标题】:Overwriting output in textfile (need to save all outputs)覆盖文本文件中的输出(需要保存所有输出)
【发布时间】:2016-11-23 03:38:11
【问题描述】:

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

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

【问题讨论】:

    标签: java text-files overwrite


    【解决方案1】:

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

    【讨论】:

    • 太棒了。感谢您的帮助! :)
    • @Suppaa 不客气,祝你好运。如果它解决了您的问题,请不要忘记将其标记为答案。
    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多