首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java IO 核心:ObjectInputStream 與 ObjectOutputStream 對象流詳解

     編輯:Java 相關知識

對象流定位

ObjectOutputStream/ObjectInputStream 是序列化的操作入口,分別包裝 OutputStream/InputStream,提供對象圖的持久化與還原能力。前提:對象必須實現 Serializable 或 Externalizable。

核心 API 概覽

ObjectOutputStream

ObjectOutputStream(OutputStream out)
void writeObject(Object obj)           // 寫入對象(含圖)
void writeInt(int v) / writeUTF(String) // 基本類型
void defaultWriteObject()              // 自定義 writeObject 中調用
void flush() / close() / reset()       // 緩衝刷新/關閉/重置引用追蹤

ObjectInputStream


ObjectInputStream(InputStream in)
Object readObject()                    // 讀取對象,需強轉
int readInt() / String readUTF()       // 基本類型
void defaultReadObject()               // 自定義 readObject 中調用
void close()

完整實戰示例


class Box implements Serializable {
    private int width, height;
    private String name;
    public Box(String n, int w, int h) { name=n; width=w; height=h; }
    @Override public String toString() { return "["+name+": ("+width+", "+height+")]"; }
}

public class ObjectStreamDemo {
    static final String FILE = "box.tmp";
    public static void main(String[] args) {
        write();
        read();
    }
    static void write() {
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(FILE))) {
            out.writeBoolean(true);
            out.writeByte((byte)65);
            out.writeChar('a');
            out.writeInt(20131015);
            out.writeFloat(3.14F);
            out.writeDouble(1.414D);
            // 寫入集合(HashMap 實現了 Serializable)
            Map map = new HashMap<>();
            map.put("one","red"); map.put("two","green"); map.put("three","blue");
            out.writeObject(map);
            // 寫入自定義對象
            out.writeObject(new Box("desk", 80, 48));
        } catch (IOException e) { e.printStackTrace(); }
    }
    static void read() {
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE))) {
            System.out.println("boolean:" + in.readBoolean());
            System.out.println("byte:" + (in.readByte()&0xff));
            System.out.println("char:" + in.readChar());
            System.out.println("int:" + in.readInt());
            System.out.println("float:" + in.readFloat());
            System.out.println("double:" + in.readDouble());
            Map map = (Map) in.readObject();
            map.forEach((k,v) -> System.out.println(k+" -- "+v));
            Box box = (Box) in.readObject();
            System.out.println("box: " + box);
        } catch (IOException|ClassNotFoundException e) { e.printStackTrace(); }
    }
}

關鍵注意點

  1. 讀寫順序絕對一致:序列化是流式的,順序錯誤導致數據錯位或 ClassCastException。
  2. 引用共享保持:同一對象多次 writeObject 只會序列化一次,後續寫入引用句柄;反序列化還原同一引用。
  3. reset():強制重置引用追蹤表,使後續 writeObject 視為新對象(用於長生命周期流防止內存洩漏)。
  4. serialVersionUID:顯式聲明避免版本不兼容導致 InvalidClassException。

總結

對象流是 Java 內置序列化的核心工具類。掌握「順序一致、引用共享、版本控制」三大鐵律,配合 BufferedXxx 提升大對象圖讀寫性能,即可構建健壯的持久化/傳輸層。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved