我在使用 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]);
行不正确,我找不到适合它的方法。错误读取类型 RandomAccessFile
中的方法 writeByte(int)
不适用于参数 (Student
)。这显然是因为 writeBytes
方法没有采用 student 类型。
最佳答案
字符串有一种非常简单的方法可以转换为字节。他们有一个运行良好的 getBytes()
方法。您可以通过重载 toString()
方法来获取学生的字符串表示形式。所以你的电话看起来很像
file.writeByte(students[i].toString().getBytes( "UTF-8" ));
编辑:
忘记了 getBytes() 返回一个字节数组。这应该有效:
byte[] bytes = students[i].toString().getBytes();
for(byte byteWrite : bytes){
file.writeByte(byteWrite);
}
关于java - 使用 RandomAccessFile 编写学生数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11833385/