序列化与反序列化
游戏存档:目的是为了游戏下次上号数据的保存
package com.yy.otherio;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;import com.yy.bean.Person;public class Demo3_ObjectOutputStream {/*** 序列化:将对象写到文件上* @throws IOException * @throws ClassNotFoundException * * ObjectInputStream * 对象输入流,是反序列化* */public static void main(String[] args) throws IOException, ClassNotFoundException {demo1();demo2();demo3();ObjectInputStream ois = new ObjectInputStream(new FileInputStream("b.txt"));ArrayList<Person> list = (ArrayList<Person>) ois.readObject(); //将集合对象第一次读取for (Person person : list) {System.out.println(person);}ois.close();}private static void demo3() throws IOException, FileNotFoundException {Person p1 = new Person("张三",23);Person p2 = new Person("李四",24);Person p3 = new Person("王五",25);Person p4 = new Person("赵六",26);ArrayList<Person> list= new ArrayList<>();list.add(p1);list.add(p2);list.add(p3);list.add(p4);ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("b.txt"));oos.writeObject(list);oos.close();}private static void demo2() throws IOException, FileNotFoundException, ClassNotFoundException {ObjectInputStream ois = new ObjectInputStream(new FileInputStream("b.txt"));Person p1 = (Person) ois.readObject();Person p2 = (Person) ois.readObject();System.out.println(p1);System.out.println(p2);ois.close();}private static void demo1() throws IOException, FileNotFoundException {Person p1 = new Person("张三",23);Person p2 = new Person("李四",24);ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("b.txt"));oos.writeObject(p1);oos.writeObject(p2);oos.close();// FileOutputStream fos = new FileOutputStream("a.txt");
// fos.write(p1);}}
package com.yy.bean;import java.io.Serializable;public class Person implements Serializable{private String name;private int age;public Person() {super();}public Person(String name, int age) {super();this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}}