java - 使用ObjectOutputStream删除特定数据

标签 java file-io objectinputstream objectoutputstream

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

最佳答案

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

关于java - 使用ObjectOutputStream删除特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5286088/

相关文章:

java - 无法创建 ObjectInputStream 对象

java - 启动 Activity 时未显示 "Enable Device Admin"的对话框

Java:分割逗号分隔的字符串但忽略引号中的逗号

java - 如何在另一个 Activity 中显示点击的 ListView 项目

java - NoSuchElementException:未找到行 - Scanner Java

Java ObjectInputStream 填充 : StreamCorruptedException in stead of EOFException

java - 使用 JasperReports API 生成报告时获取空值

c++ - 增加缓冲是否会提高 C++ 中 ifstream.getline() 的最高速度?

c# - 使用 System.Data.SQLite 在 C# 应用程序中缓慢打开 SQLite 连接

java - 在java中读取对象直到文件结束