![](/img/trans.png)
[英]How should I write a POJO representation to a RandomAccessFile?
[英]How do I write and delete Objects from a RandomAccessFile?
我目前正在做一个学校项目,需要将我的数据保存到RandomAccessFile
。 我认为这不是最有效的方法,但是我必须这样做。 注意:我必须使用RandomAccessFile类。
我知道如何将简单的strings
和在main方法中创建的int
保存到文件中,但是我很难将这些知识转移到我自己的程序中。
我有4个不同的班级,即Database
, Group
, Student
, Rehearsal
。 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.