Search code examples
javaarraysarraylistrandom-access

trouble with writing array of students using RandomAccessFile


I had some problems printing out a student store with which I used an ArrayList. I then made a static array to hold these different students and now I'm trying to find out what method I can use to write them. Here is my code:

MainApp
import java.io.RandomAccessFile;



    public class MainApp
    {

        public static void main(String[] args) throws Exception 
        {
            new MainApp().start();

        }
        public void start()throws Exception 
        {
            StudentStore details = new StudentStore();
            Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo@hotmail.com");
            Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini@gmail.com");
            Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez@webmail.com");
            Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez@yahoo.com");
            Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123@hotmail.com");
            details.add(a);
            details.add(b);
            details.add(c);
            details.add(d);
            details.add(e);
            //details.print();


            RandomAccessFile file = new RandomAccessFile("ContactDetails.txt","rw");

            Student[] students = {a,b,c,d,e};
            for (int i = 0;i < students.length;i++)
            {
                file.writeByte(students[i]);
            }
            file.close();


         }


     }

The line file.writeByte(students[i]); is incorrect and I can't find a method to suit this. The error reads the method writeByte(int) in the type RandomAccessFile is not applicable for the arguments (Student). This is obviously because writeBytes method does not take the type student.


Solution

  • Strings have a very easy way to convert into bytes. They have a getBytes() method that would work well. You can get a string representation of a student by overloading the toString() method. So your call would look a lot like

    file.writeByte(students[i].toString().getBytes( "UTF-8" ));
    

    edit:

    Forgot getBytes() returns an array of bytes. This should work:

    byte[] bytes = students[i].toString().getBytes();
    for(byte byteWrite : bytes){
        file.writeByte(byteWrite);
    }