所以我尝试将用户列表存储到外部文本文件中,如果他们还没有帐户,则他们需要注册,然后他们的帐户就会添加到文本文件中。
但是每次我创建一个新用户时,它都会覆盖文本文件中的最后一个用户。
任何人都可以看到我创建新用户的代码有什么问题吗?如果有明显的东西可以修复它?
编辑:
我相信每次运行程序时都会重新创建文本文件,我怎样才能添加到它,而不是每次都创建一个新文件?
System.out.println("Enter your full name below (e.g. John M. Smith): ");
String name = scanner.nextLine();
System.out.println("Create a username: ");
String userName = scanner.nextLine();
System.out.println("Enter your starting deposit amount: ");
double balance = scanner.nextInt();
System.out.print(dash);
System.out.print("Generating your information...\n");
System.out.print(dash);
int pin = bank.PIN();
String accountNum = bank.accountNum();
User user = new User(name, userName, pin, accountNum, balance);
// new user gets added to the array list
Bank.users.add(user);
System.out.println(user);
}
try {
File file = new File("users.text");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.append(String.valueOf(Bank.users));
bw.close();
System.out.print("DONE");
} catch (IOException e) {
e.printStackTrace();
}
最佳答案
您的问题是,当您创建 FileWriter 实例时,您并没有要求它追加。它默认为覆盖。
试试这个(上下文的额外行):
if (!file.exists()) {
file.createNewFile();
}
// Line being changed
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(String.valueOf(Bank.users));
bw.close();
关于java - 每次程序运行时创建一个新的但不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21150324/