Question

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.

Was it helpful?

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);
}

OTHER TIPS

RandomAccessFile is meant to be seek to points in the file and inject values, and I wouldn't recommend it for your purposes. If all you are trying to do is write these lines to a file I would use a BufferedWriter. It has everything you need.

BufferedWriter file= new BufferedWriter(new FileWriter(filename));

and then to write, just put:

file.write(students[i]);

I should warn you that each Student will look like garbage unless you have a custom toString() method.

If you just want to write the objects to file in non-readable format, check out BufferedOutputStream

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top