Java IO流對象的序列化和反序列化實例詳解
Java—IO流 對象的序列化和反序列化
序列化的基本操作
1.對象序列化,就是將Object轉(zhuǎn)換成byte序列,反之叫對象的反序列化。
2.序列化流(ObjectOutputStream),writeObject 方法用于將對象寫入輸出流中;
反序列化流(ObjectInputStream),readObject 方法用于從輸入流中讀取對象。
3.序列化接口(Serializeable)
對象必須實現(xiàn)序列化接口,才能進(jìn)行序列化,否則會出現(xiàn)異常。這個接口沒有任何方法,只是一個標(biāo)準(zhǔn)。
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);
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
關(guān)于阿里巴巴TransmittableThreadLocal使用解讀
文章主要介紹了三種ThreadLocal的使用:ThreadLocal、InheritableThreadLocal和TransmittableThreadLocal,ThreadLocal和InheritableThreadLocal在單線程和部分情況下可以正常工作,但TransmittableThreadLocal在處理線程池時表現(xiàn)更佳2025-02-02
詳解mybatis plus使用insert沒有返回主鍵的處理
這篇文章主要介紹了詳解mybatis plus使用insert沒有返回主鍵的處理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
Spring Boot開箱即用可插拔實現(xiàn)過程演練與原理解析
本文通過深入探討Spring Boot的背景歷史、業(yè)務(wù)場景、功能點以及底層原理,并通過Java代碼手寫模擬了Spring Boot的啟動過程和自動配置功能,為開發(fā)者提供了一個全面的理解,感興趣的朋友跟隨小編一起看看吧2024-11-11

