(JAVA)序列化
對象序列化與反序列化
對象中的數據有:new Object() 自己的成員變量
如果對象的基本數據不變,反復使用
什么是序列化
將對象中的數據以二進制方式存入硬盤,永久保存
二進制文件可以在網絡上傳輸
反序列化
將存在硬盤中的二進制文件,讀取出來還原對象中的數據寫對象的流,實現對象的序列化,Java.io.ObjectOutputStream
讀對象的流,實現對象的序列化,java.io.ObjectInputStream對象類,需要實現Serializable開啟序列化功能
靜態,成員變量,屬于自己的類,不屬于對象,不能序列化
transient 修飾成員變量,組織對象序列化
Serializable接口,
里面沒有抽象方法,實現后,不用寫任何方法,修改源代碼后,class文件不會重新計算序列號
給類,自己定義一個序列號Exception in thread "main" java.io.InvalidClassException:
Person; local class incompatible: stream classdesc serialVersionUID = 5106964254523124602,local class serialVersionUID = -3636218586871335542
import java.io.*;/*** @author Alina* @date 2021年12月11日 4:28 下午* 對象序列化*/
public class ObjectStreamDemo {public static void main(String[] args) throws IOException, ClassNotFoundException {// writeObiect();readObject();}public static void writeObiect() throws IOException {ObjectOutputStream oop = new ObjectOutputStream(new FileOutputStream("/Users/yuzhang/Desktop/IOPrctice/test2.txt"));Person p = new Person();oop.writeObject(p);oop.flush();oop.close();}public static void readObject() throws IOException, ClassNotFoundException {ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/yuzhang/Desktop/IOPrctice/test2.txt"));Object obj = ois.readObject();System.out.println(obj);}
}
總結
- 上一篇: FPGA学习 Vivado使用篇
- 下一篇: 基于java坦克大战游戏