繁体   English   中英

如何从RandomAccessFile中写入和删除对象?

[英]How do I write and delete Objects from a RandomAccessFile?

我目前正在做一个学校项目,需要将我的数据保存到RandomAccessFile 我认为这不是最有效的方法,但是我必须这样做。 注意:我必须使用RandomAccessFile类。

我知道如何将简单的strings和在main方法中创建的int保存到文件中,但是我很难将这些知识转移到我自己的程序中。

我有4个不同的班级,即DatabaseGroupStudentRehearsal Database类使您可以将组添加到组的链接列表中。 然后,您可以向每个组添加学生(见下文)以及排练日期(其剧院管理程序)。 这些分别添加到linkedlist<Student>linkedlist<Rehearsal>

这是我在Group类中的addStudent方法,可将学生添加到已创建的组的链表中。

public void addStudent(int id, String firstname, String lastname) throws IOException {
    Student newstudent = new Student(id, firstname, lastname);
    if (!Students.contains(newstudent)) {
        Students.add(newstudent);
} else 
        JOptionPane.showMessageDialog(null, "Student with ID " + id
                + " already exists in group!", "Error",
                JOptionPane.WARNING_MESSAGE);
}

执行该方法时,如何让该方法自动将学生对象写入文件?

这是我的removeStudent方法:

public void removeStudent(int id) {
    if (!Students.remove(new Student(id, null, null))) {
        JOptionPane.showMessageDialog(null, "Student with ID[" + id
                + "] not present. System unchanged.");

    } 
}

几乎是同样的问题,执行该方法后,如何从文件中删除特定对象。 如果您能在这方面帮助我,那也很棒:)

以您要写入文件的方式覆盖对象类的toString()方法!

然后在linkedlist使用foreach循环并在学生对象上调用toString()并写入文件

例:

fileOutputStream outStream=newFileOutputStream("../RandomAccessFile");//path where you want to create file
foreach(Student s in linkedlist)
{
  outStream.println(s.toString()+"/n");
}

您不能从RandomAccessFile删除任何内容,除非实现代码可以理解的某种文件协议,例如,用空值填充记录,假设文件中包含记录,并假设全空(或其他值)不是合法的记录值。 或者在每个记录上实现一个字节标题,这样1表示存在,0表示删除, 反之亦然。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM