1.
ObjectInputStream与ObjectOutputStream类所读写的对象必须实现Serializable接口,ObjectOutputStream是把对象堆中的数据存写到文件中,所以对象中的transient和static类型成员变量不会被读取和写入;
注意:如果没有实现Serializable接口,则出错。这是为了保证能把对象写入到文件,并能再把对象读回到程序中的缘故。
对数据其中转作用的是文件,ObjectOutputStream把对象存入文件, ObjectInputStream从文件中读取数据
2.import java.io.*;
public class serializtion {
public static void main(String[] args)throws IOException{
Student s1=new Student("wangwu", 1, 18, "数学"); //要被存储的对象
Student s2=new Student("lisi", 2, 19, "物理");
//把对象存入文件中
FileOutputStream fout=new FileOutputStream("student.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);out.writeObject(s1);
out.writeObject(s2);
out.close();
//从文件中读取对象
FileInputStream fin=new FileInputStream("student.txt");ObjectInputStream in=new ObjectInputStream(fin);
try {
s1=(Student) in.readObject();
s2=(Student) in.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in.close();
System.out.print("name:"+s1.name);
System.out.print(" id:"+s1.id);
System.out.print(" age:"+s1.age);
System.out.println(" department:"+s1.department);
System.out.print("name:"+s2.name);
System.out.print(" id:"+s2.id);
System.out.print(" age:"+s2.age);
System.out.println(" department:"+s2.department);
}
}
3.import java.io.*;
//要存入的对象所属的类
public class Student implements Serializable {String name;
int id ;
int age;
String department;
public Student(String name, int id, int age, String department) {
this.age = age;
this.department = department;
this.id = id;
this.name = name;
}
}