2011-03-12 101 views
0

我目前正在嘗試編寫一個程序來存儲有關人員的數據到.dat文件中。該程序必須能夠添加條目,顯示條目和刪除條目(所有這些條目都是相同類型的對象)。使用ObjectOutputStream刪除特定數據

我遇到的麻煩是刪除條目。我已被特別指示不要使用隨機訪問文件,但我需要能夠刪除特定的數據位置。我不確定如何定義要刪除的條目,因爲我無法控制任何類型的指針。我有一種方法來查找條目的位置,但我無法刪除對象位置處的數據。

private static Person findPerson(String theName) 
{ 
    Person thePerson = null; 

    try 
    { 
     inputStream = new ObjectInputStream(new FileInputStream(personFile)); 

     while(!done) //While the name has not been found 
     { 
      thePerson = (Person)inputStream.readObject(); 

      if(theName.equals(thePerson.getName())) //If the name is found 
      { 
       done = true; 
      } 
     } 
     done = false; 

     inputStream.close(); //Close the stream 
    } 

    catch(IOException e) //If the end of the file is reached 
    { 
     System.out.println("The name you specified is not in the file."); 
    } 
    catch(ClassNotFoundException e) //If there is trouble 
    { 
     System.out.println("Problems with file input."); 
    } 

    return thePerson; //Return the record 
} 

有沒有辦法讓我定義ObjectOutputStream應該去哪裏刪除數據?我將如何去刪除特定的條目?

回答

1

您可以隨時創建新的臨時文件,並在while循環中只添加您感興趣的條目。刪除舊文件並更改臨時文件名後