(JAVA)序列化
對(duì)象序列化與反序列化
對(duì)象中的數(shù)據(jù)有:new Object() 自己的成員變量
如果對(duì)象的基本數(shù)據(jù)不變,反復(fù)使用
什么是序列化
將對(duì)象中的數(shù)據(jù)以二進(jìn)制方式存入硬盤(pán),永久保存
二進(jìn)制文件可以在網(wǎng)絡(luò)上傳輸
反序列化
將存在硬盤(pán)中的二進(jìn)制文件,讀取出來(lái)還原對(duì)象中的數(shù)據(jù)寫(xiě)對(duì)象的流,實(shí)現(xiàn)對(duì)象的序列化,Java.io.ObjectOutputStream
讀對(duì)象的流,實(shí)現(xiàn)對(duì)象的序列化,java.io.ObjectInputStream對(duì)象類(lèi),需要實(shí)現(xiàn)Serializable開(kāi)啟序列化功能
靜態(tài),成員變量,屬于自己的類(lèi),不屬于對(duì)象,不能序列化
transient 修飾成員變量,組織對(duì)象序列化
Serializable接口,
里面沒(méi)有抽象方法,實(shí)現(xiàn)后,不用寫(xiě)任何方法,修改源代碼后,class文件不會(huì)重新計(jì)算序列號(hào)
給類(lèi),自己定義一個(gè)序列號(hào)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 下午* 對(duì)象序列化*/
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);}
}
總結(jié)
- 上一篇: FPGA学习 Vivado使用篇
- 下一篇: 基于java坦克大战游戏