//需求 : 生成 5个学生并使它们存放在文件中,用到序列化和反序列化 package Zuoye01; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; public class SerializeTest { public static void main(String[] args) { List <Student> stus = new ArrayList<>(); stus.add(new Student("小笑", 19, "男")); stus.add(new Student("小龙", 24, "男")); stus.add(new Student("张三", 18, "男")); stus.add(new Student("雪莉", 17, "女")); stus.add(new Student("小华", 19, "女")); // 用序列化和反序列化 // 1 要记得实现Serializeable.. 才能具有能序列化和反序列化的功能 // 2 先写出地址 输出 :FileOutputStream / 输入:FileInputStream // 再分别写ObjectOutPutStream / ObjectInputStream两个类 // 应该先输出 程序=> 文件夹 写 FileOutputStream fos = null; ObjectOutputStream os = null; // 输入 再读取 文件夹 = > 程序 FileInputStream fis = null; ObjectInputStream ois = null; //开始输出 try { fos = new FileOutputStream("D:/MyDemo/Student.txt"); fis = new FileInputStream("D:/MyDemo/Student.txt"); try { os = new ObjectOutputStream(fos); os.writeObject(stus); //序列化成功 os.flush(); //开始读取 //开始反序列化 ois = new ObjectInputStream(fis); try { List<Student> stu1 = (List<Student>)ois.readObject(); for (int i = 0; i < stus.size(); i++) { System.out.println("我的名字是:"+stus.get(i).getName()); System.out.println("我的年龄是:"+stus.get(i).getAge()); System.out.println("我的性别是:"+stus.get(i).getGender()); System.out.println("--------------------- "); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { ois.close(); fis.close(); os.close(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package Zuoye01; import java.io.Serializable; public class Student implements Serializable{ //创建学生类模板 private String name; private int age; private String gender; public Student(String name, int age, String gender) { super(); this.name = name; this.age = age; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }