0

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 :)

Nino
  • 17
  • 1
  • 9

2 Answers2

0

override the toString() method of object class in the way you want to write to the file!

then loop using foreach over the linkedlist and call toString() on student object and write to file

example:

fileOutputStream outStream=newFileOutputStream("../RandomAccessFile");//path where you want to create file
foreach(Student s in linkedlist)
{
  outStream.println(s.toString()+"/n");
}
Nomesh Gajare
  • 855
  • 2
  • 12
  • 28
  • Thanks, but this is not a RandomAccessFile, is it? Because I need to save my data using the RandomAccessFile class and I need to use the seek method when writing, deleting or reading from file. – Nino Apr 09 '13 at 09:35
0

You can't delete anything from a RandomAccessFile except by implementing some file protocol that your code understands, for example filling a record with nulls, assuming your file has records, and assuming that all-nulls (or whatever) is not a legal record value. Or implement a byte header on each record such that 1 means present and 0 means deleted, or vice versa.

user207421
  • 305,947
  • 44
  • 307
  • 483