【问题标题】:Delete specific data using ObjectOutputStream使用 ObjectOutputStream 删除特定数据
【发布时间】:2011-03-12 22:52:20
【问题描述】:

我目前正在尝试编写一个程序来将有关人员的数据存储到 .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 应该去哪里删除数据?我将如何删除特定条目?

【问题讨论】:

    标签: java file-io objectinputstream objectoutputstream


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-02-03
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2021-04-18
      • 2017-01-15
      相关资源
      最近更新 更多