IO操作。问题描述程序功能:在网络传输过程中,对象数据往往需要进行序列化操作,即将对象序列化为byte数组,同时也需要反序列化操作将byte数组转化为对象。下面程序中定义了一个Stud...
IO操作。
问题描述
程序功能:在网络传输过程中,对象数据往往需要进行序列化操作,即将对象序列化为byte数组,同时也需要反序列化操作将byte数组转化为对象。下面程序中定义了一个Student类,在该类中已经实现了反序列化操作,请完成序列化的操作代码。
程序结构如下
import java.io.*;
class Student {
int stuNo; // 学号
String name; // 姓名
String sex;// 性别
int age;// 年龄
String grade;// 年级
String classname;// 班级
public Student(int stuNo, String name, String sex, int age, String grade, String classname) {
this.stuNo = stuNo;
this.name = name;
this.sex = sex;
this.age = age;
this.grade = grade;
this.classname = classname;
}
// 反序列化操作
public static Student GetStudent(byte[] byteStudent) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(byteStudent);
DataInputStream dis = new DataInputStream(bais);
int stuNo = dis.readInt();
String name = dis.readUTF();
String sex = dis.readUTF();
int age = dis.readInt();
String grade = dis.readUTF();
String classname = dis.readUTF();
return new Student(stuNo, name, sex, age, grade, classname);
} catch (Exception ex) {
return null;
}
}
// 序列化操作,请完成
public byte[] GetBytes() {
// 补充此处代码
}
}
public class Exam2 {
public static void main(String args[]) {
Student stu = new Student(20090223, "java", "man", 21, "三年级", "2班");
byte[] bytestu = stu.GetBytes();
Student stul = Student.GetStudent(bytestu);
System.out.println(stul.stuNo);
}
}
程序要求
1.实现序列化代码
展开