要序列化的了类需要实现Serializable
接口
package com.mouday; import java.io.Serializable; public class Person implements Serializable { // 序列化前后的唯一标识符 private static final long serialVersionUID = 1; private String name; private int age; private int score; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", score=" + score + '}'; } }
序列化和反序列化
import com.mouday.Person; import org.junit.Test; import java.io.*; public class TestDemo { @Test public void serialize() throws IOException { Person person = new Person(); person.setAge(23); person.setName("Tom"); ObjectOutputStream objectOutputStream = new ObjectOutputStream( new FileOutputStream( new File("person.txt") ) ); objectOutputStream.writeObject(person); objectOutputStream.close(); } @Test public void deserialize() throws IOException, ClassNotFoundException { ObjectInputStream objectInputStream = new ObjectInputStream( new FileInputStream( new File("person.txt") ) ); Person person = (Person)objectInputStream.readObject(); objectInputStream.close(); System.out.println(person); // Person{name='Tom', age=23} } }
参考