[英]How to write multiple text in file without overwriting it
I have created a simple program that will create a bank account and balance This program will ask the number of accounts you want to create then you will input account number and balances. 我创建了一个简单的程序,它将创建一个银行帐户和余额。该程序将询问您要创建的帐户数,然后输入帐户号和余额。
Now the problem is when its writing new account number it just Overwriting it, so the text that entering in my file is only 1 line; 现在的问题是,当它写入新帐号时,它只是覆盖它,因此输入我文件中的文本只有1行;
Here's my current code: 这是我当前的代码:
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!");
}
}
Thank you, hope you will answer this question 谢谢,希望你能回答这个问题
// 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);
The Java tutorials and the javadoc are your friends. Java教程和Javadoc是您的朋友。 Use them. 使用它们。
Your method createBank
stores only the last inputs for account and balance in the variables and addRecords
is only called once. 您的方法createBank
仅将帐户和余额的最后输入存储在变量中,并且addRecords
仅被调用一次。
Call addRecords
inside the loop in createBank
and createFile
before createBank
. 呼叫addRecords
在循环内createBank
和createFile
前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();
}
}
And add a newline in addRecords
. 并在addRecords
添加换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.