序列化 - readObject writeObject 重写

12 浏览
0 Comments

序列化 - readObject writeObject 重写

我已经编写了下面的代码,现在我需要在StudentData中使用自定义的readObject()和writeObject()覆盖方法来读取和写入对象的变量。不使用defaultWriteObject或defaultReadObject方法来实现。

问题是我不完全理解我被要求做什么。我已经阅读了Uses of readObject/writeObject in Serialization,但我无法理解。有人可以指点我吗?

我的代码:

import java.io.*; //引入输入输出文件

class Student implements java.io.Serializable {

String name; //变量声明

String DOB;

int id;

Student(String naam, int idno, String dob) //将变量初始化为用户数据

{

name = naam;

id = idno;

DOB = dob;

}

public String toString() {

return name + "\t" + id + "\t" + DOB + "\t";

}

}

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

class StudentData //主类

{

public static void main(String args[]) throws IOException //异常处理

{

System.out.println("请输入学生人数:");

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

int n = Integer.parseInt(in.readLine());

Student[] students = new Student[n];

//Student[] S=new Student[n]; //对象数组声明和定义

for (int i = 0; i < students.length; i++) {

System.out.println("请输入第" + (i + 1) + "个学生的详细信息:"); //从用户读取数据

System.out.println("姓名:");

String naam = in.readLine();

System.out.println("学号:");

int idno = Integer.parseInt(in.readLine());

System.out.println("出生日期:");

String dob = (in.readLine());

students[i] = new Student(naam, idno, dob);

File studentFile = new File("StudentData.txt");

try {

FileOutputStream fileOutput = new FileOutputStream(studentFile);

ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);

objectOutput.writeObject(students);

students = null;

FileInputStream fileInput = new FileInputStream(studentFile);

ObjectInputStream objectInputStream = new ObjectInputStream(fileInput);

students = (Student[]) objectInputStream.readObject();

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

for (Student student : students) {

System.out.println(student);

}

}

}

}

0