一般情况下在网络传输对象或者把不活动的对象保存保存到本地时才做序列化操作,以减少服务器中内存的占用。做序列化的对象必须实现序列化接口。
1.在要序列化的类中必须实现序化接口
import java.io.Serializable;
public class User implements Serializable { //给定一个序列化版本,拥有相同的版本才能反序列化,增加或减少字段也不会影响反序列化,因为他们的版本号是固定的 PRivate static final long serialVersionUID = 1L; transient String passWord;//瞬时字段不写到反序列化中去 private String name; private int age; public User(String name, int age, String password) { this.name = name; this.age = age; this.password = password; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ",password=" + password + "]"; }}
2.测试类的编写
public class MyTest { public static void main(String[] args) throws Exception { File f = new File("g:/a.text"); //做序列操作,把对象写到本地文件或者服务器中去,减少服务器中的内存的占用 writeObject(f); //反序列化操作 readObject(f); } private static void writeObject(File f) throws Exception { User user = new User("张三", 18, "abc"); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f)); out.writeObject(user); } private static void readObject(File f) throws Exception { ObjectInputStream in = new ObjectInputStream(new FileInputStream(f)); User user = (User) in.readObject(); System.out.println(user); }}
新闻热点
疑难解答