用Java 对象流写一个学生集合序列化
时间: 2023-07-19 10:27:51 浏览: 87
好的,下面是实现代码:
首先,我们需要定义一个 `Student` 类,该类需要实现 `Serializable` 接口,以便能够被序列化和反序列化。
```java
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
接下来,我们需要创建一个包含多个 `Student` 对象的集合,这里我们使用 `ArrayList`。
```java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class SerializeStudent {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student(1, "Tom", 18));
students.add(new Student(2, "Jerry", 19));
students.add(new Student(3, "Mike", 20));
students.add(new Student(4, "John", 21));
students.add(new Student(5, "Lucy", 22));
}
}
```
最后,我们使用 `ObjectOutputStream` 将集合对象序列化到文件中。
```java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class SerializeStudent {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student(1, "Tom", 18));
students.add(new Student(2, "Jerry", 19));
students.add(new Student(3, "Mike", 20));
students.add(new Student(4, "John", 21));
students.add(new Student(5, "Lucy", 22));
try {
FileOutputStream fileOut = new FileOutputStream("students.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(students);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in students.ser");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
以上代码中,我们将 `ArrayList` 对象 `students` 序列化到文件 `students.ser` 中。如果一切顺利,程序会输出 "Serialized data is saved in students.ser"。
阅读全文