I am currently working on a school project for which I need to save my data to a RandomAccessFile
. I figured that this is by far not the most efficient way, but I have to do it. Note: I have to use the RandomAccessFile class.
I understand how I can save simple strings
and int
created in the main method to a file, but I am having trouble transferring this knowledge onto my own program.
I have 4 different classes, i.e. Database
, Group
, Student
, Rehearsal
. The Database
class lets you add groups to a linked list of groups. To each group, you can then add students (see below) as well as rehearsal dates (its a theatre management program). These are added to linkedlist<Student>
and linkedlist<Rehearsal>
respectively.
This is my addStudent
method in the Group
class that adds a student to the linkedlist of a group that was created.
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);
}
How do I let the method automatically write the student object to the file when it is executed?
This is my removeStudent
method:
public void removeStudent(int id) {
if (!Students.remove(new Student(id, null, null))) {
JOptionPane.showMessageDialog(null, "Student with ID[" + id
+ "] not present. System unchanged.");
}
}
Pretty much the same question, how can I then delete a specific object from the file when the method is executed. If you could me help me out on that as well, that would be great :)