如何在文件中写入多个文本而不覆盖它

时间:2015-01-26 07:51:22

标签: java file io formatter

我创建了一个简单的程序,可以创建银行帐户和余额 该程序将询问您要创建的帐户数量,然后您将输入帐号和余额。

现在的问题是,当它编写新的帐号时,它只是覆盖它,所以输入我文件的文本只有1行;

这是我目前的代码:

    import java.util.*;

import javax.swing.JOptionPane;

public class CreateBankFile {
    public static Formatter sample;
    public static int account;
    public static int balance;
    public static void main(String[] args) {
        createBank();
        createFile();
        addRecords();
        closeFile();
    }

    public static void createBank() {
        int loops = Integer.parseInt(JOptionPane.showInputDialog(null,
                "How many accounts \nyou wanted to create?"));
        for (int i = 1; i <= loops; i++) {
            account = Integer.parseInt(JOptionPane.showInputDialog(null,
                    "Enter account number:"));
            balance = Integer.parseInt(JOptionPane.showInputDialog(null,
                    "Enter balance:"));
        }
    }

    public static void createFile() {
        try {
            sample = new Formatter("BankAccounts.txt");
        } catch (Exception e) {
            System.out.println("You got an error!");
        }
    }

    public static void addRecords() {
        sample.format("%s%s", account + "\t", balance);
    }

    public static void closeFile() {
        sample.close();
        JOptionPane.showMessageDialog(null, "You successfully created bank accounts!");
    }
}

谢谢,希望你能回答这个问题

2 个答案:

答案 0 :(得分:0)

// create an output stream to the file in append mode rather than overwrite mode
FileOutputStream out = new FileOutputStream("BankAccounts.txt", true);
// create a Formatter which writes to this stream
Formatter formatter = new Formatter(out);

Java教程和javadoc是你的朋友。使用它们。

答案 1 :(得分:0)

您的方法createBank仅存储变量中帐户和余额的最后输入,addRecords仅调用一次。
addRecords之前调用createBankcreateFile createBank之前调用public static void main(String[] args) { createFile(); createBank(); closeFile(); } public static void createBank() { int loops = Integer.parseInt(JOptionPane.showInputDialog(null, "How many accounts \nyou wanted to create?")); for (int i = 1; i <= loops; i++) { account = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter account number:")); balance = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter balance:")); addRecords(); } }

addRecords

在{{1}}中添加换行符。