两个常用的工具类(经常使用)

一.首先创建一个可以进行序列化的类 创建类的时候前面加上[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

posted @ 2018-08-30 22:19  Hard_Song  阅读(260)  评论(0编辑  收藏  举报