1. 程式人生 > >兩個常用的工具類(經常使用)

兩個常用的工具類(經常使用)

persist iter per pan src edi cnblogs n) ali

一.首先創建一個可以進行序列化的類 創建類的時候前面加上[Serializable](需要註意的是想要打出序列化需要引入的命名空間為 using System;)

二.然後寫入一些類的基本屬性設置為共有方法

技術分享圖片

三.然後寫入如下代碼就能夠很快捷的實現生成XML

技術分享圖片

 #region XML序列化第一種方法
 //Xml序列化工具
 static string fileName;
 public static void SaveData<T>(T saveData) where T : new()
 {
     Encoding utf8NoBom = new UTF8Encoding(false
); fileName = Application.dataPath + "/" + saveData.GetType().ToString(); Stream stream = new FileStream(fileName,FileMode.OpenOrCreate,FileAccess.Write); StreamWriter sw = new StreamWriter(stream,utf8NoBom); XmlSerializer xmlSerializer = new XmlSerializer(saveData.GetType()); xmlSerializer.Serialize(sw,saveData); sw.Dispose(); stream.Dispose(); }
public static T ReadData<T>() where T : new() { T data = new T(); string site = Application.dataPath + "/" + data.GetType().ToString(); Stream str = new FileStream(site, FileMode.Open, FileAccess.Read, FileShare.None); StreamReader reader = new StreamReader(str, true); XmlSerializer xml
= new XmlSerializer(data.GetType()); data = (T)xml.Deserialize(reader); reader.Close(); str.Close(); return data; } #endregion

2.實現講一個電腦上的文件路徑打包到手機上也能進行使用

思路:首先將需要進行移動的文件放入到StreamIngAssets文件夾下,在這個路徑下的文件在電腦端能進行讀寫操作,在手機端只能進行讀操作,所以在想要在手機端進行文件的寫操作,需要將StreamingAssets中的文件轉到沙盒路徑下:

public static void CopyFileFromSAPathTOPDPath(string InSAName,string INPDPName=null,Action InOnCopyFinshedAction=null)
{
    Assert.IsFalse(string.IsNullOrEmpty(InSAName));
    if (string.IsNullOrEmpty(INPDPName))
    {
        INPDPName = InSAName;
    }
    string streamingAssetPath = Path.Combine(Application.streamingAssetsPath,InSAName);
    string persistentDataPath = Path.Combine(Application.persistentDataPath,INPDPName);
    #if !UNITY_EDITOR && UNITY_ANDROID
                using (WWW www=new WWW(streamingAssetPath))
            {
                while (!www.isDone){}
 
                if (www.isDone&&string.IsNullOrEmpty(www.error))
                {
                    File.WriteAllBytes(persistentDataPath,www.bytes);
                    if (null!=InOnCopyFinshedAction)
                    {
                        InOnCopyFinshedAction.Invoke();
                    }
                    else
                    {
                        Debug.LogError("下載錯誤:"+www.error);
                    }
                }
            }
    #else
            File.Copy(streamingAssetPath,persistentDataPath,true);
            if (null!=InOnCopyFinshedAction)
            {
                InOnCopyFinshedAction.Invoke()
            }
    #endif
}

以上就是兩個經常進行使用的工具類,希望能幫助到大家,大家有不懂得或者我錯的,歡迎在下方評論區進行評論,大家一起學習,謝謝!!!!!

文章轉自:https://www.cnblogs.com/baosong/p/9563071.html

兩個常用的工具類(經常使用)