0

我目前正在尝试编写一个程序来将有关人员的数据存储到 .dat 文件中。程序必须能够添加条目、显示条目和删除条目(所有这些都是同一类型的对象)。

我遇到的麻烦是删除条目。我被明确指示不要使用随机访问文件,但我需要能够删除特定位置的数据。我不确定如何定义要删除的条目,因为我无法控制任何类型的指针。我有一种查找条目位置的方法,但我无法删除对象位置的数据。

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 应该去哪里删除数据?我将如何删除特定条目?

4

1 回答 1

1

您始终可以创建新的临时文件并在 while 循环中仅添加您感兴趣的条目。在删除旧文件并更改临时文件名之后

于 2011-03-12T22:58:02.953 回答