Java 如何在不覆盖文件的情况下在文件中写入多个文本
我已经创建了一个简单的程序,将创建一个银行帐户和余额 此程序将询问您要创建的帐户数,然后输入帐户号和余额 现在的问题是,当它写新账号时,它只是覆盖了它,所以在我的文件中输入的文本只有1行 以下是我当前的代码:Java 如何在不覆盖文件的情况下在文件中写入多个文本,java,file,io,formatter,Java,File,Io,Formatter,我已经创建了一个简单的程序,将创建一个银行帐户和余额 此程序将询问您要创建的帐户数,然后输入帐户号和余额 现在的问题是,当它写新账号时,它只是覆盖了它,所以在我的文件中输入的文本只有1行 以下是我当前的代码: import java.util.*; import javax.swing.JOptionPane; public class CreateBankFile { public static Formatter sample; public static int
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!");
}
}
谢谢,希望你能回答这个问题
// 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是您的朋友。使用它们。您的方法createBank只在变量中存储account和balance的最后输入,并且只调用一次addRecords。
在createBank之前,在createBank和createFile中的循环内调用addRecords
并在addRecords中添加一个换行符。关于如何用Java编写文件的教程数不胜数……您需要添加新文本,而不仅仅是写入。可能是另一个重复的Thank You,但它仍在一行中写入,我想把它放在另一行中\n但它仍在继续,请确保附加到文件的行的末尾包含换行符。没有。示例。格式%s%s%s,帐户+\t,余额,\n;这就是我更改的代码,还是我需要以另一种方式更改所有代码?像追加?我不使用appendI,我会将\n放入模式本身:它根本不是动态的。如果在Windows上,我将使用\r\n:sample.format%s\t%s\r\n,account,balance;
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();
}
}