国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

java筆記九:對象序列化與反序列化

2019-11-17 03:27:27
字體:
來源:轉載
供稿:網友

  在java程序運行過程中,有許多的對象同時存在,但是程序結束運行或者JVM停止運行時這些對象都會消失。如何將這些對象保存起來以便下一次再將這些對象讀入內存呢?或者如何將某些對象通過網絡傳到另一端的java程序?實施對象的這種操作叫做對象的序列化(或者叫做持久化),重新讀入內存叫做反序列化。

  基本數據類型的包裝類和所有容器類都可以被序列化。用戶自定義的類默認是不可以被序列化的。如果想要自己定義的類可以序列化就必須讓這個類實現java.io.Serializable接口。

下面看一個Demo:


 1 package com.serializable;
 2
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.ObjectInputStream;
 8 import java.io.ObjectOutputStream;
 9 import java.io.Serializable;
10
11 class Point implements Serializable{
12     PRivate int x;
13     private int y;
14     private transient int z;  //用關鍵字transient修飾的屬性不能參與序列化的過程
15     public Point(int x,int y,int z) {
16         this.x = x;
17         this.y = y;
18         this.z = z;
19     }
20     @Override
21     public String toString() {
22         return "(" + x + "," + y + "," + z + ")";
23     }
24 }
25
26 public class ObjectSerializableDemo {
27    
28    
29     public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
30         String fileName = "F://shar//test//test7.txt";
31         //將二進制文件轉換成一個對象輸出流
32         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
33         for (int i = 0; i < 10; i++) {
34             oos.writeObject(new Point(i,2*i,3*i));
35         }
36         oos.flush();
37         oos.close();
38        
39         ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
40         for (int i = 0; i < 10; i++) {
41             Point p = (Point)ois.readObject();
42             System.out.println(p + " ");
43         }
44         ois.close();
45     }
46
47 }

運行結果:
(0,0,0)
(1,2,0)
(2,4,0)
(3,6,0)
(4,8,0)
(5,10,0)
(6,12,0)
(7,14,0)
(8,16,0)
(9,18,0)

  從運行結果可以看出,所有Piont類對象的z屬性都沒有被序列化。應為它被一個關鍵字transient修飾了,被這個關鍵字修飾的屬性是不參與持久化的。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新泰市| 绿春县| 西乌珠穆沁旗| 凉城县| 襄垣县| 建宁县| 乐昌市| 中西区| 焦作市| 砀山县| 两当县| 长兴县| 肥西县| 昌乐县| 万宁市| 新兴县| 嘉祥县| 临安市| 衡南县| 金堂县| 嵊泗县| 广平县| 年辖:市辖区| 轮台县| 青岛市| 正镶白旗| 阳信县| 阿荣旗| 南阳市| 甘德县| 万宁市| 循化| 东安县| 南京市| 桦南县| 怀安县| 荔浦县| 曲水县| 金门县| 新乡市| 诸城市|