Java—IO流 對象的序列化和反序列化

  • 序列化的基本操做

  1.對象序列化,就是將Object轉換成byte序列,反之叫對象的反序列化。java

  2.序列化流(ObjectOutputStream),writeObject 方法用於將對象寫入輸出流中;spa

  反序列化流(ObjectInputStream),readObject 方法用於從輸入流中讀取對象。code

  3.序列化接口(Serializeable)對象

  對象必須實現序列化接口,才能進行序列化,不然會出現異常。這個接口沒有任何方法,只是一個標準。blog

package com.test.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectSerialzeTest {
    /**
     * 對象的序列化
     * @param file
     * @throws Exception
     */
    public void ObjectOutput (String file) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        Student stu = new Student("002", "張四", 12);
        oos.writeObject(stu);
        oos.flush();
        oos.close();
    }
    /**
     * 對象的反序列化
     * @param file
     * @throws Exception
     */
    public void ObjectInput(String file) throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        Student stu =  (Student)ois.readObject();
        System.out.println(stu.toString());
        ois.close();
    }

    public static void main(String[] args)  throws Exception {
        String file = "F:\\javaio\\obj.dat";
        ObjectSerialzeTest ost = new ObjectSerialzeTest();
        ost.ObjectOutput(file);
        ost.ObjectInput(file);
    }
}
相關文章
相關標籤/搜索