一、Java序列化介绍
1.Java序列化与反序列化
Serialization(序列化)是一种将对象以一连串的字节描述的过程;
deserialization(反序列化)是一种将这些字节重建成一个对象的过程。
2.为什么需要反序列化
Java中,一切都是对象,在分布式中经常需要将Object从这一端网络或设备传递到另一端。这就需要有一种可以在两端传输数据的协议。
Java序列化机制就是为了解决这个问题。......
3.JDK类库中序列化API
Java.io.ObjectOutPutStream 表示对象输出流
(writeObject(Object obj))对指定的对象序列化
Java.io.ObjectInPutStream 表示对象输入流
(readObject())对输入流进行反序列化
4.实现序列化的要求
实现Serializable或Extermalizable接口类的对象才能被序列化,否则抛出异常
二、Java序列化的实现
1.实现Serializable的对象序列化
public class TestSerial implements Serializable { public String name = "15pb"; public String getName(){ return name; } }
public class Main { //Create objectStream public static void onCreateStream() throws IOException { FileOutputStream fos = new FileOutputStream("temp.out"); ObjectOutputStream oos = new ObjectOutputStream(fos); TestSerial ts = new TestSerial(); oos.writeObject(ts); oos.flush(); oos.close(); } //reader objectStream public static void reader() throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream("temp.out"); ObjectInput oin = new ObjectInputStream(fis); TestSerial ts = (TestSerial) oin.readObject(); System.out.println("name= "+ts.getName()); } public static void main(String[] args) throws IOException, ClassNotFoundException { // write your code here onCreateStream(); reader(); } }
2.实现Extermalizable接口对象的序列化
public class TestExter implements Externalizable { public String name ; public String Student ; public void setName(String name){ this.name = name; } public void setStudent(String student){ this.Student = student; } public String toString(){ return "name= "+this.name+" ,Student= "+this.Student; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(name); out.writeObject(Student); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { name = (String) in.readObject(); Student = (String) in.readObject(); } }
public class Main{
public static void main(String[] args) throws IOException, ClassNotFoundException { // write your code here //write ObjectStream TestExter testExter = new TestExter(); testExter.setName("15pb"); testExter.setStudent("hx"); FileOutputStream out = new FileOutputStream("Exter.out"); ObjectOutputStream obj = new ObjectOutputStream(out); obj.writeObject(testExter); //reader ObjectStream FileInputStream in = new FileInputStream("Exter.out"); ObjectInputStream input = new ObjectInputStream(in); TestExter ts = (TestExter) input.readObject(); System.out.println(ts.toString()); } }