【问题标题】:How to delete an object that are written into file?如何删除写入文件的对象?
【发布时间】:2015-07-09 01:10:42
【问题描述】:

在我的程序中,用户提供了一些输入,这些输入被添加到 arrayList 中。 arrayList 对象被写入文件。因此,我创建了一个用于写入和读取文件的方法(使用 file-i/o 和 object-i/o 流)。

现在如果我想从文件中删除特定对象,我该怎么做?

这是我正在处理的部分:

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;

【问题讨论】:

标签: java list file-io arraylist fileoutputstream


【解决方案1】:

我认为最简单的解决方案是将文件中的所有对象读入ArrayList。然后从上述列表中删除您要删除的那个。最后,用列表中的新内容覆盖文件的初始内容。

如果您不想重新读取文件的内容并且您有对内存中对象列表的引用,那么您可以删除该对象并覆盖文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 2011-09-20
    相关资源
    最近更新 更多