我一直试图用Java创建一个简单的银行帐户,并希望保存输入的用户'将名称命名为.txt文档。唯一的问题是每次运行代码时,文本doc的第一行都会替换名称。
package bank.account;
import java.util.Scanner;
import java.io.*;
public class ATM
{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
BankAccount userAccount = new BankAccount();
System.out.println("Please enter your name in order to make a new account:");
String fileName = "name.txt";
try {
FileWriter fileWriter =
new FileWriter(fileName);
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
String name = sc.nextLine();
userAccount.setaccName(name);
bufferedWriter.write(userAccount.getaccName());
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
}
System.out.println("Please enter the amount you would like to deposit");
double money = sc.nextDouble();
userAccount.deposit(money);
System.out.println(userAccount.getaccBalance());
System.out.println(userAccount.getaccName()+ " your balance is " + userAccount.getaccBalance());
}
}
答案 0 :(得分:2)
由于使用new FileWriter(fileName, true);
,您正在覆盖文件内容(请阅读该类/构造函数上的JavaDoc)。请改为使用"\n"
追加到文件中。
另请注意,如果文件不为空,则需要在名称前附加换行符({{1}}),否则您将获得一行中的所有名称。
答案 1 :(得分:2)
此代码将打开或创建一个文件,并将新文本追加到新行中。
PrintStream fileStream = new PrintStream(new File("a.txt"));
fileStream.println(userAccount.getaccName());
您也可以使用参数“ append = true ”创建FileWriter
,然后将结果添加到新行中。
// FileWriter(File file, boolean append)
FileWriter fileWriter =
new FileWriter(filePathName, shouldAppend);