1、ObjectOutputStream、ObjectInputStream
序列化和反序列化
对应的类实现
implements Serializable
编写Person类,包含姓名、年龄、体重等属性,提供对应的访问方法;
编写测试类1,在main方法中创建三个不同的Person对象,将这三个对象序列化到文件中;
编写测试类2,在main方法中从文件中反序列化三个Person对象,打印输出。验证序列化的正确;
在测试类1中,将三个Person对象放到数组中,序列化该数组到一个独立的文件中。
再将三个Person对象放到List集合中,序列化该集合到另一个独立的文件中;
在测试类2中,将三个Person对象从数组文件中反序列化,并打印;
将三个Person对象从List集合文件中反序列,并打印。验证数组对象和集合对象的序列化。
package com.xian; import java.io.*; import java.util.ArrayList; public class Test818 { public static void main(String[] args) { Person person=new Person("罗翔",49,66); Person person1=new Person("罗翔1",49,66); Person person2=new Person("罗翔2",49,66); Person[] per={person,person1,person2}; System.out.println("**************数组***************"); main1(per); ArrayList<Person> people=new ArrayList<>(); people.add(person); people.add(person1); people.add(person2); System.out.println("*****************集合***************"); main2(people); try { System.out.println("*************对象流**************"); ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File("./obj.txt"))); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("./obj.txt"))); oos.writeObject(person); oos.writeObject(person1); oos.writeObject(person2); System.out.println(ois.readObject()); System.out.println(ois.readObject()); System.out.println(ois.readObject()); } catch (Exception e) { e.printStackTrace(); } } public static void main1(Person[] per) { try { ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File("./obj1.txt"))); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("./obj1.txt"))); oos.writeObject(per); Person[] perplo= (Person[]) ois.readObject(); for (Person person : perplo) { System.out.println(person); } } catch (Exception e) { e.printStackTrace(); } } public static void main2(ArrayList<Person> list) { try { ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File("./obj2.txt"))); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("./obj2.txt"))); oos.writeObject(list); System.out.println(ois.readObject()); System.out.println(ois.readObject()); System.out.println(ois.readObject()); } catch (Exception e) { e.printStackTrace(); } } }