本文以一个简单的小例子,简述对象持久化的相关知识,仅供学习分享使用,如有不足之处,还请指正。
概述
对象持久化是指将内存中的对象保存到可永久保存的存储设备中(如磁盘)的一种技术。
本文介绍的是除数据库之外的几种对象持久化方式。
具体如下:
- 保存成文本:即将内存对象以字节流的方式保存到文本中。
- 序列化成Xml:即将对象以Xml的格式存储。
- 序列化成Json:即将对象序列化成Json对象,然后存储。
- 序列化成二进制:即将对象序列化成二进制字节流保存到文件中。
涉及知识点:
- 序列化与反序列化
- 文件流的读写
- ListView显示复选框,并横向排列
效果图
如下图所示【主要功能是将用户输入的信息保存成各种格式,并从各个文档中进行读取出来】:
核心代码
保存和读取文本文档代码如下:
1 /// <summary> 2 /// 保存成文本 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void btnSaveTxt_Click(object sender, EventArgs e) 7 { 8 Dictionary<string, string> dicInfos = GetDictionaryInfos(); 9 string filePath = "objPerson.txt"; 10 //采用using关键字,会自动释放 11 using (FileStream fs = new FileStream(filePath, FileMode.Create)) 12 { 13 using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) 14 { 15 foreach (var keyPair in dicInfos) 16 { 17 sw.WriteLine(string.Format("{0}={1}", keyPair.Key, keyPair.Value)); 18 } 19 } 20 } 21 } 22 23 /// <summary> 24 /// 从文本中读取 25 /// </summary> 26 /// <param name="sender"></param> 27 /// <param name="e"></param> 28 private void btnReadTxt_Click(object sender, EventArgs e) 29 { 30 string filePath = "objPerson.txt"; 31 Dictionary<string, string> dic = new Dictionary<string, string>(); 32 //采用using关键字,会自动释放 33 using (FileStream fs = new FileStream(filePath, FileMode.Open)) 34 { 35 using (StreamReader sw = new StreamReader(fs, Encoding.Default)) 36 { 37 while (!sw.EndOfStream) { 38 string lineInfo = sw.ReadLine(); 39 dic.Add(lineInfo.Split('=')[0], lineInfo.Split('=')[1]); 40 } 41 } 42 } 43 this.txtName.Text = dic["Name"]; 44 this.dtBirthday.Text = dic["Birthday"]; 45 if (dic["Gender"] == this.rbBoy.Text) 46 { 47 this.rbBoy.Checked = true; 48 } 49 else { 50 this.rbGirl.Checked = true; 51 } 52 string[] loves = dic["Love"].Split('|'); 53 foreach (var love in loves) 54 { 55 foreach (var item in this.lsvLove.Items) 56 { 57 ListViewItem li = item as ListViewItem; 58 if (li.Text == love) 59 { 60 li.Checked = true; 61 } 62 } 63 } 64 }
保存和读取Xml文档代码如下:
1 /// <summary> 2 /// 保存成Xml 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void btnSaveXml_Click(object sender, EventArgs e) 7 { 8 Person p = GetPersonInfos(); 9 string filePath = "objPerson.xml"; 10 using (FileStream fs = new FileStream(filePath, FileMode.Create)) 11 { 12 XmlSerializer serializer = new XmlSerializer(typeof(Person)); 13 serializer.Serialize(fs, p); 14 } 15 } 16 17 /// <summary> 18 /// 从Xml中读取 19 /// </summary> 20 /// <param name="sender"></param> 21 /// <param name="e"></param> 22 private void btnReadXml_Click(object sender, EventArgs e) 23 { 24 string filePath = "objPerson.xml"; 25 Person p; 26 using (FileStream fs = new FileStream(filePath, FileMode.Open)) 27 { 28 XmlSerializer serializer = new XmlSerializer(typeof(Person)); 29 object obj= serializer.Deserialize(fs); 30 p = obj as Person; 31 } 32 SetPersonInfos(p); 33 }
保存和读取Json文档如下:
1 /// <summary> 2 /// 保存成Json 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void btnSaveJson_Click(object sender, EventArgs e) 7 { 8 Person p = GetPersonInfos(); 9 JavaScriptSerializer jserializer = new JavaScriptSerializer(); 10 string strJson = jserializer.Serialize(p); 11 string strRegex = @"\/Date((d+))\/"; 12 MatchEvaluator evaluator = new MatchEvaluator(ConvertJsonDateToDateString); 13 14 //对时间进行处理,需要引用System.Text.RegularExpressions;命名空间 15 Regex reg = new Regex(strRegex); 16 strJson = reg.Replace(strJson, evaluator); 17 18 string filePath = "objPerson.json"; 19 using (FileStream fs = new FileStream(filePath, FileMode.Create)) 20 { 21 using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) 22 { 23 sw.Write(strJson); 24 } 25 } 26 } 27 28 /// <summary> 29 /// 从Json中读取 30 /// </summary> 31 /// <param name="sender"></param> 32 /// <param name="e"></param> 33 private void btnReadJson_Click(object sender, EventArgs e) 34 { 35 JavaScriptSerializer jserializer = new JavaScriptSerializer(); 36 string filePath = "objPerson.json"; 37 Person p; 38 using (FileStream fs = new FileStream(filePath, FileMode.Open)) 39 { 40 using (StreamReader sw = new StreamReader(fs, Encoding.Default)) 41 { 42 string strJson = sw.ReadToEnd(); 43 string strRegex = @"d{4}-d{2}-d{2}sd{2}:d{2}:d{2}"; 44 MatchEvaluator evaluator = new MatchEvaluator(ConvertDateStringToJsonDate); //对时间进行处理 45 Regex reg = new Regex(strRegex); 46 strJson = reg.Replace(strJson, evaluator); 47 p = jserializer.Deserialize<Person>(strJson); 48 } 49 } 50 SetPersonInfos(p); 51 }
保存和读取Bin文档如下:
1 /// <summary> 2 /// 保存成二进制文件 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void btnSaveBin_Click(object sender, EventArgs e) 7 { 8 Person p = GetPersonInfos(); 9 string filePath = "objPerson.bin"; 10 using (FileStream fs = new FileStream(filePath, FileMode.Create)) { 11 BinaryFormatter bf = new BinaryFormatter(); 12 bf.Serialize(fs, p); 13 } 14 } 15 16 /// <summary> 17 /// 读取二进制文件 18 /// </summary> 19 /// <param name="sender"></param> 20 /// <param name="e"></param> 21 private void btnReadBin_Click(object sender, EventArgs e) 22 { 23 string filePath = "objPerson.bin"; 24 Person p; 25 using (FileStream fs = new FileStream(filePath, FileMode.Open)) 26 { 27 BinaryFormatter bf = new BinaryFormatter(); 28 p= bf.Deserialize(fs) as Person; 29 } 30 SetPersonInfos(p); 31 }
备注
其实对象持久化和对象序列化是两个不同的概念。两者有关联却不同。
对象持久化:是使对象可以保存到实体存储介质中,在对象生命周期结束后可以再现。
对象序列化:是将对象或者数据结构转化成特定的格式,使其可在网络中传输,或者可存储在内存或者文件中。
源码下载链接