我的写文本是错误的吗?

Joh*_*ohn 1 java arraylist try-catch

我有一个文件叫"CI.txt"

在文件内部,信息​​是:

Mr Abc;ABC;abc123;Abc Road;428428;VISA;2222111144442222
Mr Efg;EFG;efg123;Efg Road;424213;MASTERCARD;4444555566667777
Mr Lmn;LMN;lmn123;Lmn Road;492482;VISA;9999000011112222
Run Code Online (Sandbox Code Playgroud)

这是我的代码,它工作得很好,但问题是..

for (Customer ci : custList){
//Compares the username and userpassword
//If correct, set new card number and card type..
if (inputUser.equals(ci.getUserName()) && inputPass.equals(ci.getPassword())) {
     ci.setCardNo(newCardNo);
     ci.setCardType(newCardType);
}

     String text = ci.getRealName() + ";" + ci.getUserName() + ";" + ci.getPassword() + ";" + ci.getContact() + ";" + ci.getcardType() + ";" + ci.getcardNo();
     try {
         File fileCI = new File("CI.txt");
         FileWriter fileWriter = new FileWriter(fileCI);
         BufferedWriter bw = new BufferedWriter(fileWriter);
         bw.write(text);
         bw.close();
     }
     catch (FileNotFoundException e) {
     System.out.println("File not found");
     }
     catch (IOException e) {
     System.out.println("Unable to write to file");
     }                                     
}
Run Code Online (Sandbox Code Playgroud)

我的输出只有Lmn先生的记录.没有Abc先生的记录,我更新了新的信用卡类型和号码.为什么会这样?我System.out.println(text)在try语句中做了所有内容都正确打印出来.有人可以帮忙吗?

Mar*_*nik 5

您在for循环的每次迭代中打开和关闭文件.默认情况下打开文件会删除其中的所有内容.您必须在启动for循环之前打开文件,然后才关闭它.