因此,我试图将用户列表存储到外部文本文件中,如果他们还没有帐户,那么他们需要注册,他们的帐户将被添加到文本文件中。
但是,每次创建新用户时,它都会覆盖文本文件中的最后一个用户。
有人能看到我的代码在创建一个新用户时有什么问题吗?如果有什么明显的东西可以修复它呢?
编辑:
我相信,每当我运行程序时,文本文件都会被重新创建,我如何才能添加到其中,而不是每次创建一个新的文件呢?
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();
}
发布于 2014-01-15 15:20:51
您的问题是,当您创建您的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();
发布于 2014-01-15 15:20:44
像这样的事情应该有效:
String filename= "users.test";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write(String.valueOf(Bank.users));//appends the string to the file
fw.close();
试试看。一定要在课程之外添加一些例外和其他东西。
发布于 2014-01-15 15:21:07
这是因为文件在打开时得到截断的。您必须在附加模式下打开它,其中包括:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
第二个参数将告诉FileWriter
这样做。参考这里。
https://stackoverflow.com/questions/21150324
复制