I/O(输入/输出)---序列化与反序列化
生活随笔
收集整理的這篇文章主要介紹了
I/O(输入/输出)---序列化与反序列化
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
概念:
序列化就是將對象的狀態(tài)存儲到特定的介質(zhì)中的過程,也就是將對象狀態(tài)轉(zhuǎn)換為可保持或傳輸格式的過程。
反序列化則是從特定存儲介質(zhì)中將數(shù)據(jù)重新構(gòu)建對象的過程。可以將存儲在文件上的對象信息讀取,然后重新構(gòu)建為對象。
?
過程:
將對象的公有成員、私有成員包括類名,轉(zhuǎn)換為字節(jié)流---》寫入數(shù)據(jù)流---》存儲到存儲介質(zhì)中(文件)。
意義:
將java對象序列化后,可以將其轉(zhuǎn)換為自己序列,這樣就可以保存在磁盤上,也可以借助網(wǎng)絡(luò)進(jìn)行傳輸。
對象的保存是二進(jìn)制狀態(tài),實現(xiàn)了平臺的無關(guān)性。
import java.io.Serializable; /** Serializable:用于給被序列化的類加入ID號。* 用于判斷類和對象是否是同一個版本。 */ //Person誒實現(xiàn)Serializable接口,代表這個類可被序列化 public class Person implements Serializable/*標(biāo)記接口*/ {/*** transient:非靜態(tài)數(shù)據(jù)不想被序列化可以使用這個關(guān)鍵字修飾。 */private static final long serialVersionUID = 9527l;private transient String name;private static int age;public Person(String name, int age) {super();this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}?
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import cn.itcast.io.p2.bean.Person;public class ObjectStreamDemo {/*** @param args* @throws IOException * @throws ClassNotFoundException */public static void main(String[] args) throws IOException, ClassNotFoundException {// writeObj(); readObj();}public static void readObj() throws IOException, ClassNotFoundException {//ObjectInputStream 對象輸入流ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.object"));//對象的反序列化。需要類型轉(zhuǎn)換。 Person p = (Person)ois.readObject();System.out.println(p.getName()+":"+p.getAge());ois.close();}public static void writeObj() throws IOException, IOException {//ObjectInputStream 對象輸出流ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.object"));//對象序列化。 被序列化的對象必須實現(xiàn)Serializable接口。 oos.writeObject(new Person("小強(qiáng)",30));oos.close();}}?
轉(zhuǎn)載于:https://www.cnblogs.com/fifiyong/p/6010652.html
總結(jié)
以上是生活随笔為你收集整理的I/O(输入/输出)---序列化与反序列化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓与HTML简单的交互使用
- 下一篇: 邮箱密码验证-原理