题目
定义一个可序列化的对象Student类,这个类实现了Serializable接口,类中的成员变量id,name,age,department都可以被序列化,方法不能序列化。通过对象输出流的writeObject()方法将Student对象保存到文件data.ser中, 然后通过对象输入流的readObject()方法从文件data.ser中读出保存下来的Student对象,然后将Student对象的id和name输出到控制台 。
代码
class student implements Serializable {
private static final long SerializableUID = 10000000000 l;
private int stuno;
private String name;
private int score;
public student ( int stuno, String name, int score) {
this . stuno = stuno;
this . name = name;
this . score = score;
}
public int getStuno ( ) {
return stuno;
}
public void setStuno ( int stuno) {
this . stuno = stuno;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public int getScore ( ) {
return score;
}
@Override
public boolean equals ( Object o) {
if ( this == o) return true ;
if ( o == null || getClass ( ) != o. getClass ( ) ) return false ;
student student = ( student) o;
return stuno == student. stuno;
}
@Override
public int hashCode ( ) {
return Objects. hash ( stuno) ;
}
@Override
public String toString ( ) {
return "student{" +
"stuno=" + stuno +
", name='" + name + '\'' +
", score=" + score +
'}' ;
}
public void setScore ( int score) {
this . score = score;
}
}
public class Test04 {
public static void main ( String[ ] args) {
ObjectOutputStream os = null;
ObjectInputStream is = null;
try {
os = new ObjectOutputStream ( new FileOutputStream ( "stu.txt" ) ) ;
is = new ObjectInputStream ( new FileInputStream ( "stu.txt" ) ) ;
student stu1 = new student ( 194041201 , "张三" , 90 ) ;
student stu2 = new student ( 194041202 , "李四" , 30 ) ;
student stu3 = new student ( 194041203 , "王五" , 70 ) ;
student stu4 = new student ( 194041204 , "赵六" , 97 ) ;
os. writeObject ( stu1) ;
os. writeObject ( stu2) ;
os. writeObject ( stu3) ;
os. writeObject ( stu4) ;
Object o1 = is. readObject ( ) ;
System. out. println ( o1) ;
Object o2 = is. readObject ( ) ;
System. out. println ( o2) ;
Object o3 = is. readObject ( ) ;
System. out. println ( o3) ;
Object o4 = is. readObject ( ) ;
System. out. println ( o4) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
}
}
}