3

我在打印一个学生商店时遇到了一些问题,我使用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方法不带学生类型。

4

2 回答 2

3

字符串有一种非常简单的方法可以将其转换为字节。他们有一种getBytes()行之有效的方法。toString()您可以通过重载该方法来获取学生的字符串表示形式。所以你的电话看起来很像

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

编辑:

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

byte[] bytes = students[i].toString().getBytes();
for(byte byteWrite : bytes){
    file.writeByte(byteWrite);
}
于 2012-08-06T17:59:11.703 回答
0

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

于 2012-08-06T18:01:31.250 回答