2015-04-29 25 views
0

在我的程序中,用戶給出了一些輸入,並將這些輸入添加到arrayList中。 arrayList對象被寫入文件。因此,我創建了一個用於寫入和讀取文件的方法(使用文件I/O &對象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; 
+2

重寫沒有內容的文件? – kolossus

+0

kolossus,什麼? – Munira

+0

「[如何]在文件中查找一行並將其刪除」http://stackoverflow.com/questions/1377279/find-a-line-in-a-file-and-remove-it – CubeJockey

回答

2

在我腦海中最簡單的辦法是從文件中的所有對象讀入ArrayList。然後從上述列表中刪除要刪除的那個。最後,用列表中的新內容覆蓋文件的初始內容

如果你不想重新讀取文件的內容,你必須在內存中的對象的列表的引用,那麼你可以刪除對象和覆蓋該文件的內容

+0

最簡單和** *正確的***解決方案。 –