只有实现了Serializable或Externalizable接口的类的对象才能被序列化,否则抛出异常。
假定一个Student类,它的对象需要序列化,可以有如下三种方法:
方法一:若Student类仅仅实现了Serializable接口,则可以按照以下方式进行序列化和反序列化
ObjectOutputStream采用默认的序列化方式,对Student对象的非transient的实例变量进行序列化。
ObjcetInputStream采用默认的反序列化方式,对对Student对象的非transient的实例变量进行反序列化。
方法二:若Student类仅仅实现了Serializable接口,并且还定义了readObject(ObjectInputStream in)和writeObject(ObjectOutputSteam out),则采用以下方式进行序列化与反序列化。
ObjectOutputStream调用Student对象的writeObject(ObjectOutputStream out)的方法进行序列化。
ObjectInputStream会调用Student对象的readObject(ObjectInputStream in)的方法进行反序列化。
方法三:若Student类实现了Externalnalizable接口,且Student类必须实现readExternal(ObjectInput in)和writeExternal(ObjectOutput out)方法,则按照以下方式进行序列化与反序列化。
ObjectOutputStream调用Student对象的writeExternal(ObjectOutput out))的方法进行序列化。
ObjectInputStream会调用Student对象的readExternal(ObjectInput in)的方法进行反序列化。
- public class UseStudent
- {
- public static void main(String[] args)
- {
- Student st = new Student("Tom",'M',20,3.6);
- File file = new File("O:\\Java\\com\\jieke\\io\\student.txt");
- try
- {
- file.createNewFile();
- }
- catch(IOException e)
- {
- e.printStackTrace();
- }
- try
- {
- //Student对象序列化过程
- FileOutputStream fos = new FileOutputStream(file);
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(st);
- oos.flush();
- oos.close();
- fos.close();
- //Student对象反序列化过程
- FileInputStream fis = new FileInputStream(file);
- ObjectInputStream ois = new ObjectInputStream(fis);
- Student st1 = (Student) ois.readObject();
- System.out.println("name = " + st1.getName());
- System.out.println("sex = " + st1.getSex());
- System.out.println("year = " + st1.getYear());
- System.out.println("gpa = " + st1.getGpa());
- ois.close();
- fis.close();
- }
- catch(ClassNotFoundException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- }