假设我有一个 Student
类的对象,它具有以下字段:
String name;
int age;
int roll_number;
我像这样实例化:
Student A[] = new Student();
现在,有没有办法使用文件处理将所有这些信息存储在文本文件中?
我想过循环遍历数组中的每个元素,然后将所有字段转换为字符串,但这似乎是错误的。
最佳答案
另一种方法是使用 Serialization 。您的 Student
类必须实现 Serialized
:
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private int rollNumber;
//...
}
然后读取和写入 Student
数组:
try {
Student[] students = new Student[3];
//Write Student array to file.
FileOutputStream fos = new FileOutputStream("students.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(students);
oos.close();
//Read Student array from file.
FileInputStream fis = new FileInputStream("students.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student[] studentsFromSavedFile = (Student[]) ois.readObject();
ois.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
关于java - 如何在 Java 中将对象数组写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34626970/