在我的程序中,用户提供了一些输入,并将这些输入添加到arrayList中。 arrayList对象被写入文件。因此,我有一个用于写入和读取文件的创建方法(使用file-i / o& object-i / o stream)。
现在如果我想从文件中删除特定对象,我该怎么做?
这是我工作的一部分:
case 4:
bankAccounts2=(List<BankAccount>)rw.readFromFile();//method calling; BankAccount is the class for settre and getter
Iterator<BankAccount> it=bankAccounts2.iterator();//bankAccounts2 is the arrayList for reading file
System.out.println("Enter the account you want to delete:");
deleteAcc = sc.nextInt();
while (it.hasNext()) {
BankAccount next = it.next();
if (next.getAccNum() == deleteAcc) {
it.remove();
}
}
break;
答案 0 :(得分:2)
我认为最简单的解决方案是将文件中的所有对象都读入ArrayList
。然后从上述列表中删除要删除的那个。最后,使用列表中的新内容覆盖文件的初始内容。
如果您不想重新读取文件的内容并且您对内存中的对象列表有引用,那么您只需删除该对象并覆盖的内容即可。文件