使用RandomAccessFile编写学生数组的麻烦

时间:2012-08-06 17:54:39

标签: java arrays arraylist random-access

我打印出一个使用ArrayList的学生商店时遇到了一些问题。然后我制作了一个静态数组来容纳这些不同的学生,现在我试图找出我可以用来编写它们的方法。这是我的代码:

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


         }


     }

file.writeByte(students[i]);行不正确,我无法找到适合此方法的方法。错误读取writeByte(int)类型中的方法RandomAccessFile不适用于参数(Student)。这显然是因为writeBytes方法不接受学生类型。

2 个答案:

答案 0 :(得分:3)

字符串有一种非常简单的方法可以转换成字节。他们有一个getBytes()方法可以很好地工作。您可以通过重载toString()方法来获取学生的字符串表示形式。所以你的电话看起来很像

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

编辑:

忘记getBytes()返回一个字节数组。这应该有效:

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

答案 1 :(得分:0)

RandomAccessFile旨在寻找文件中的点并注入值,我不建议将其用于您的目的。如果您要尝试将这些行写入文件,我将使用BufferedWriter。它拥有您需要的一切。

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

然后写,只是把:

file.write(学生[I]);

我应该警告你,除非你有自定义的toString()方法,否则每个学生都会看起来像垃圾。

如果您只想以不可读的格式将对象写入文件,请查看BufferedOutputStream