持久化工具类

时间:2022-03-14 03:48:55
using UnityEngine; 
using System.Collections; 
using System.Xml; 
using System.Xml.Serialization; 
using System.IO;
using System.Text;
/// <summary>
/// 持久化工具类
/// </summary>
public class Persistence : MonoBehaviour {
	
	//持久化文件路径
	static string FileLocation = Application.dataPath + "//StreamingAssets//Xml//Persistence//";
	
	/// <summary>
	/// 保存数据到XML
	/// </summary>
	public static void Save(string fileName, object obj){
		CreateXML(fileName,SerializeObject(obj));
	}
	
	/// <summary>
	/// 加载XML数据
	/// </summary>
	public static object Load(string fileName, System.Type type){
		return DeserializeObject(type,LoadXML(fileName));
	}
	
	/// <summary>
	/// 序列化对象
	/// </summary>
	public static string SerializeObject(object pObject) 
   	{
		string XmlizedString = null;
		MemoryStream memoryStream = new MemoryStream(); 
		XmlSerializer xs = new XmlSerializer(pObject.GetType());
		XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); 
		xs.Serialize(xmlTextWriter, pObject); 
		memoryStream = (MemoryStream)xmlTextWriter.BaseStream; 
		XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
		return XmlizedString; 
   	}
	
	/// <summary>
	/// 反序列化对象
	/// </summary>
	public static object DeserializeObject(System.Type type,string pXmlizedString) 
	{ 
		XmlSerializer xs = new XmlSerializer(type); 
		MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); 
		XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); 
		return xs.Deserialize(memoryStream); 
	}

	/// <summary>
	/// 将二进制转换为字符串
	/// </summary>
	public static string UTF8ByteArrayToString(byte[] characters) 
	{      
		UTF8Encoding encoding = new UTF8Encoding(); 
		string constructedString = encoding.GetString(characters); 
		return (constructedString); 
	}
 
	/// <summary>
	/// 将字符串转换为二进制
	/// </summary>
	public static byte[] StringToUTF8ByteArray(string pXmlString) 
	{
		UTF8Encoding encoding = new UTF8Encoding(); 
		byte[] byteArray = encoding.GetBytes(pXmlString); 
		return byteArray; 
	}

	/// <summary>
	/// 创建XML文件
	/// </summary>
	public static void CreateXML(string fileName,string dataStr) 
	{ 
		StreamWriter writer; 
		FileInfo t = new FileInfo(FileLocation+"//"+ fileName + ".xml"); 
		if(!t.Exists){ 
			writer = t.CreateText(); 
		}else{ 
			t.Delete(); 
			writer = t.CreateText(); 
		} 
		writer.Write(dataStr); 
		writer.Close();
	} 

	/// <summary>
	///加载XML文件
	/// </summary>
	public static string LoadXML(string fileName) 
	{ 
		StreamReader r = File.OpenText(FileLocation+"//"+ fileName + ".xml"); 
		string info = r.ReadToEnd(); 
		r.Close(); 
		return info; 
	}
}