0

In my program, user gives some inputs and those are added into an arrayList. The arrayList object are written into file. Thus I have a created method for writing into and read from file (using file-i/o & object-i/o stream).

Now If I want to delete a particular object from the file, how do I do that?

This is the part of I am workin on:

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;
Munira
  • 153
  • 16

1 Answers1

2

The easiest solution in my mind is to read all the objects from the file into an ArrayList. Then remove the one you want to delete from the aforementioned list. Finally, overwrite the initial contents of the file with the new contents in the list.

If you do not want to re-read the contents of the file and you have a reference to the list of objects in memory, then you can just remove the object and overwrite the contents of the file

KernelKoder
  • 746
  • 5
  • 15