1. package com.neusoft.test1; //首先定义一个被序列化的类

  2. import java.io.Serializable;

  3. class Student implements Serializable {// 定义一个可以被序列化的类

  4. String name;

  5. int age;

  6. String num;

  7. double score;

  8. public Student() {

  9. }

  10. public Student(String name, int age, String num, double score) {

  11. this.name = name;

  12. this.age = age;

  13. this.num = num;

  14. this.score = score;

  15. }

  16. public String toString() {

  17. return name + "\t" + age + "\t" + num + "\t" + score;

  18. }

  19. }

...............................................

定义一个用于将Student对象序列化的类

 
    
  1. package com.neusoft.test1;

  2. import java.io.File;

  3. import java.io.FileOutputStream;

  4. import java.io.IOException;

  5. import java.io.ObjectOutputStream;

  6. publicclass SerializableTest {

  7. publicstaticvoid main(String[] args) {

  8. Student stu_1 = new Student("wjl", 25, "47843847", 89);// 实例化两个可以被序列化的student对象

  9. Student stu_2 = new Student("yxm", 23, "47856547", 99);

  10. File f = new File("c:/demo/456.txt");// 保存两个对象的文件对象

  11. try {

  12. FileOutputStream fos = new FileOutputStream(f);

  13. ObjectOutputStream oos = new ObjectOutputStream(fos);

  14. System.out.println("没有被序列化时的对象如下:");

  15. System.out.println(stu_1);

  16. System.out.println(stu_2);

  17. oos.writeObject(stu_1);

  18. oos.writeObject(stu_2);

  19. System.out.println("序列化成功!!");

  20. oos.flush();

  21. fos.close();

  22. oos.close();

  23. } catch (IOException e) {

  24. e.printStackTrace();

  25. }

  26. }

  27. }

...............................................

定义一个用于将Student对象反序列化的类

 
    
  1. package com.neusoft.test1;

  2. import java.io.File;

  3. import java.io.FileInputStream;

  4. import java.io.IOException;

  5. import java.io.ObjectInputStream;

  6. publicclass TurnSerializableTest {

  7. publicstaticvoid main(String[] args) {

  8. File f = new File("c:/demo/456.txt");

  9. try {

  10. FileInputStream fis = new FileInputStream(f);

  11. ObjectInputStream ois = new ObjectInputStream(fis);

  12. Student stu_1;

  13. stu_1 = (Student) ois.readObject();

  14. System.out.println(stu_1);

  15. Student stu_2 = (Student) ois.readObject();

  16. System.out.println(stu_2);

  17. fis.close();

  18. ois.close();

  19. } catch (ClassNotFoundException e) {

  20. e.printStackTrace();

  21. } catch (IOException e) {

  22. e.printStackTrace();

  23. }

  24. }

  25. }