import java.io.Serializable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; /** * Java序列化是不能序列化static变量的 * 序列化反序列化方案 * 1 - 修饰符 static和transient * 2 - readObject和writeObject方法 * 3 - Serializable 接口 不重写也可以操作序列,反序列。(性能较低占用空间可能偏大,但是使用频率高) * 4 - Externalizable接口 重写readExternal和writeExternal方法(决定保存对象,速度高,但是使用频率低) */ public class 序列化与反序列化 { static class Person implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String name; private int age; public static String test = "IBM"; 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; } } static class Main { public static void main(String[] args) { Person person = new Person(); // person.setAge(25); // person.setName("YXY"); //Person.test = "JAVA"; //modify the test value File file = new File("/Users/christopoher/Desktop/book"); //序列化 try { OutputStream out = new FileOutputStream(file); ObjectOutputStream objout = new ObjectOutputStream(out); objout.writeObject(person); objout.close(); } catch (IOException e) { e.printStackTrace(); } //code segment 1 Person perobj = null; // 反序列化 try { InputStream in = new FileInputStream(file); ObjectInputStream objin = new ObjectInputStream(in); perobj = (Person) objin.readObject();//恢复流中的非静态和非瞬态字段 System.out.println(perobj.test); in.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } }
序列化与反序列化I 浅谈
最新推荐文章于 2023-10-30 16:12:29 发布