using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class xmlxuleihua : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
/* TestSerial t1 = XmlDeSerlize();
Debug.Log(t1.Id);*/
BinarySerTest();
}
//开始序列化
/* void XmlSerilize(TestSerial testSerial)
{
FileStream fileStream =new FileStream(Application.dataPath+"/test.xml",FileMode.Create,FileAccess.ReadWrite,FileShare.ReadWrite);//打开文件流
StreamWriter writer = new StreamWriter(fileStream,System.Text.Encoding.UTF8);//写入流
XmlSerializer serializer = new XmlSerializer(testSerial.GetType());//获取类型
serializer.Serialize(writer, testSerial);
writer.Close();
fileStream.Close();
}
TestSerial XmlDeSerlize()
{
FileStream fs = new FileStream(Application.dataPath + "/test.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
XmlSerializer xs = new XmlSerializer(typeof(TestSerial));
TestSerial testSerial =(TestSerial) xs.Deserialize(fs);
fs.Close();
return testSerial;
}*/
void BinarySerTest()
{
TestSerial testSerial = new TestSerial();
testSerial.Name = "1";
testSerial.Id = 1;
BinarySerlize(testSerial);
TestSerial testSerial1 = BinaryDeserlize();
print(testSerial1.Id);
}
void BinarySerlize(TestSerial testSerial)
{
FileStream fs = new FileStream(Application.dataPath + "/test.bytes", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
BinaryFormatter bf=new BinaryFormatter();
bf.Serialize(fs, testSerial);
fs.Close();
}
TestSerial BinaryDeserlize()
{
TextAsset textAsset = UnityEditor.AssetDatabase.LoadAssetAtPath<TextAsset>("Assets/test.bytes");
MemoryStream stream = new MemoryStream(textAsset.bytes);
BinaryFormatter bf = new BinaryFormatter();
TestSerial testSerial= (TestSerial)bf.Deserialize(stream);
stream.Close();
return testSerial;
}
}
二进制序列化反序列化
于 2022-09-21 22:40:30 首次发布