ObjectOutputStream/ObjectInputStream 是序列化的操作入口,分別包裝 OutputStream/InputStream,提供對象圖的持久化與還原能力。前提:對象必須實現 Serializable 或 Externalizable。
ObjectOutputStream(OutputStream out)
void writeObject(Object obj) // 寫入對象(含圖)
void writeInt(int v) / writeUTF(String) // 基本類型
void defaultWriteObject() // 自定義 writeObject 中調用
void flush() / close() / reset() // 緩衝刷新/關閉/重置引用追蹤
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(); }
}
}
ClassCastException。writeObject 只會序列化一次,後續寫入引用句柄;反序列化還原同一引用。writeObject 視為新對象(用於長生命周期流防止內存洩漏)。InvalidClassException。對象流是 Java 內置序列化的核心工具類。掌握「順序一致、引用共享、版本控制」三大鐵律,配合 BufferedXxx 提升大對象圖讀寫性能,即可構建健壯的持久化/傳輸層。