Java 序列化流的使用

1. ObjectOutputStream 對象的序列化流

/*
ObjectOutputStream對象的序列化流
構造方法
(1)ObjectOutputStream(OutputStream out);創建寫入指定OutputStream的ObjectOutputStream對象
特有的成員方法:
void writeObject(Object obj);將指定對象寫入ObjectOutputStream
*/

private static void oos01() throws IOException {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(".\\person.txt"));
    oos.writeObject(new person("AA",15));
    oos.close();
}

2. ObjectInputStream對象的反序列化流

/*
ObjectInputStream對象的反序列化流
構造方法
ObjectInputStream(inputStream in);創建讀取指定InputStream的ObjectInputStream對象
特有的成員方法:
Object readObject();從ObjectInputStream中讀取對象
*/
private static void os01() throws Exception {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(".\\person.txt"));
    person p = (person)ois.readObject();
    System.out.println(p.getName());
    ois.close();
}

注:person對象必須實現Serializable接口

序列化注意事項

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章