unity csv 文件读取 工具封装

1 篇文章 0 订阅

这套封装可以通过读取不同的csv文件,根据不同的枚举类型获取对应的数据

using SevenG;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
#region CSV解析的数据model
/// <summary>
/// EChart数据model
/// </summary>

public class CsvEChartMode
{
    /// <summary>
    /// EChart编号
    /// </summary>
    public int EChartNum;
    /// <summary>
    /// EChart名称
    /// </summary>
    public string EChartName;
    /// <summary>
    /// EChart路径
    /// </summary>
    public string EChartURL;
    /// <summary>
    /// 备注
    /// </summary>
    public string remark;
}

/// <summary>
/// Config数据model
/// </summary>
public class CsvConfigMode
{
    /// <summary>
    /// EChart编号
    /// </summary>
    public int ConfigNum;
    /// <summary>
    /// Config名称
    /// </summary>
    public string ConfigName;
    /// <summary>
    /// Config路径
    /// </summary>
    public string ConfigURL;
    /// <summary>
    /// 备注
    /// </summary>
    public string remark;
}
#endregion
#region  解析下载后CSV数据

interface ICSVAnalysis
{
     List<object> AnalySis(List<string[]> data);

}
/// <summary>
///  Echarts解析下载后CSV数据
/// </summary>
public class EChartsAnalysis: ICSVAnalysis
{

    public  List <object>AnalySis(List<string[]> data)
    {
        List<object> listCsv = new List<object>();
        int tabelHead = 3;

        for (int i= tabelHead;i<data.Count;i++)
        {
            CsvEChartMode mode = new CsvEChartMode();
            bool isSuccess= int.TryParse(data[i][0], out mode.EChartNum);
            if(!isSuccess)
            {
                Debug.LogError("EchartsAnalysis.AnalySis :"+ data[i][0] +"->转int类型失败");
            }

            mode.EChartName = data[i].Length > 1 ? data[i][1] : string.Empty;
            mode.EChartURL = data[i].Length>2? data[i][2]: string.Empty;
            mode.remark = data[i].Length > 3 ? data[i][3] : string.Empty;
            listCsv.Add(mode);
        }

        return listCsv;
    }
}

/// <summary>
///  Config解析下载后CSV数据
/// </summary>
public class ConfigAnalysis : ICSVAnalysis
{
    public  List<object> AnalySis(List<string[]> data)
    {
        List<object> listCsv = new List<object>();
        int tabelHead = 3;

        for (int i = tabelHead; i < data.Count; i++)
        {
            CsvConfigMode mode = new CsvConfigMode();
            bool isSuccess = int.TryParse(data[i][0], out mode.ConfigNum);
            if (!isSuccess)
            {
                Debug.LogError("EchartsAnalysis.AnalySis :" + data[i][0] + "->转int类型失败");
            }

            mode.ConfigName = data[i].Length > 1 ? data[i][1] : string.Empty;
            mode.ConfigURL = data[i].Length > 2 ? data[i][2] : string.Empty;
            mode.remark = data[i].Length > 3 ? data[i][3] : string.Empty;
            listCsv.Add(mode);
        }

        return listCsv;
    }
}
#endregion
/// <summary>
/// 关键索引,所有CSV文件关键字段集合
/// </summary>
public enum CsvEChartsType
{
    #region ECharts

    #endregion



}
public enum CsvConfigType
    {
    #region Config

    #endregion
}

public class LoadConfig : MonoBehaviour
{
    public static LoadConfig Instance;
    Dictionary<Enum, object> dicCsvMode = new Dictionary<Enum, object>();

    public bool isLoading = true;
    int index = 0;
    private List<string> fileNameList = new List<string>();
    Dictionary<string, ICSVAnalysis> fileAnalysisDic = new Dictionary<string, ICSVAnalysis>();
    Dictionary<string, Type> fileEnumlisDic = new Dictionary<string, Type>();
    int loadIndex = 0;
    private void Awake()
    {
        Instance = this;
        Debug.Log("开始下载");
        Init();
        StartCoroutine(DownLoadData(fileNameList[loadIndex]));

    }
    void Init()
    {
        ConfigCSVFileName();
    }
    /// <summary>
    /// 配置CSV文件名,并配置对应的解析CSV文件的类
    /// </summary>
    private void ConfigCSVFileName()
    {
        ICSVAnalysis csv;
        fileNameList.Add("ECharts");
        fileAnalysisDic.Add("ECharts", csv = new EChartsAnalysis());
        fileEnumlisDic.Add("ECharts",typeof(CsvEChartsType));
        fileNameList.Add("Config");
        fileAnalysisDic.Add("Config", csv = new ConfigAnalysis());
        fileEnumlisDic.Add("Config", typeof(CsvConfigType));
    }

    private void SetIP()
    {
        CsvConfigMode mode = GetMode<CsvConfigMode>(CsvConfigType.IP地址);
        UrlAddres.strServerAPI = mode.ConfigURL;
        Debug.Log(UrlAddres.strServerAPI);
    }
    public IEnumerator DownLoadData(string fileName)
    {
        isLoading = true;
        if (!fileAnalysisDic.ContainsKey(fileName))
        {
            yield return null;
        }
        //下载ECharts.csv
        List<object> model = new List<object>();
        yield return model = fileAnalysisDic[fileName].AnalySis(CSVLoad.ReadCSV(fileName));
        PushCsvDataDic(model,fileEnumlisDic[fileName]);
        model.Clear();
        loadIndex += 1;
        if (loadIndex < fileNameList.Count)
        {

            StartCoroutine(DownLoadData(fileNameList[loadIndex]));
        }
        else
        {
            isLoading = false;
            SetIP();


        }
    }
    void PushCsvDataDic(List<object> modeList, Type csvEnum)
    {
        int count = Enum.GetValues(csvEnum).Length;
        if (count != modeList.Count)
        {
            Debug.LogError(csvEnum + ":枚举个数 和数据 匹配不一致");

        }
        else if (count == modeList.Count)
        {
            int j = 0;
            foreach (var v in Enum.GetValues(csvEnum))
            {
                if(j<modeList.Count)
                {
                    dicCsvMode.Add((Enum)v, modeList[j]);
                    j++;
                }              
            }
        }
    }



    public void DownLoad(string fileName,Action<string,List<string[]>> callback)
    {
       if(callback!=null)
        {
            callback(fileName, CSVLoad.ReadCSV(fileName));
        } 

    }
    private void OnDestroy()
    {
        Instance = null;
    }
    public T GetMode<T>(Enum type) where T : class
    { 

        T mode;
        try
        {
             mode = dicCsvMode[type] as T;
        }
        catch
        {
            return default(T);
        }
        return mode;       
    }


}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Text;

public class CSVLoad  {

    //文件名返回路径
    public static string FileCSV(string _fileName)
    {
        string path = "";
#if UNITY_STANDALONE
        path = Application.dataPath + "/StreamingAssets/CSV/" + _fileName + ".csv";
#elif UNITY_EDITOR
        path = Application.dataPath + "/StreamingAssets/CSV/" + _fileName + ".csv";
#elif UNITY_IPHONE
    path = Application.dataPath + "/Raw/Csv/" + _str + ".csv";
#elif UNITY_ANDROID
    path = "jar:file://" + Application.dataPath + "!/assets/CSV/"+ _str +".csv";
#endif
        Debug.Log(path);
        return path;
    }
    //解析文件
    public static List<string[]>  ReadCSV(string _fileName)
    {
      //  Debug.Log("解析");
        List<string[]> data = new List<string[]>();
        string path = FileCSV(_fileName);
        if (File.Exists(path))
        {

            try
            {
                StreamReader srReadFile = new StreamReader(path,Encoding.UTF8);
                while (!srReadFile.EndOfStream)
                {
                    //检索出行
                    UTF8Encoding utf8 = new UTF8Encoding();
                   string value = utf8.GetString(utf8.GetBytes(srReadFile.ReadLine())) ;
                    string[] values = value.Split(',');
                    data.Add(values);
                    // Debug.Log(value);
                }
                // 关闭读取流文件
                srReadFile.Close();
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message+"请检查本地文件是否打开");
            }         

        }
        else
        {
            WWW www = new WWW(path);
            while (!www.isDone) { }

            MemoryStream stream = new MemoryStream(www.bytes);
            StreamReader reader = new StreamReader(stream);
            while (!reader.EndOfStream)
            {
                //检索出行
                UTF8Encoding utf8 = new UTF8Encoding();
                string value = utf8.GetString(utf8.GetBytes(reader.ReadLine()));
                string[] values = value.Split(',');
                data.Add(values);
                 Debug.Log(value);
            }
            stream.Close();
            reader.Close();

            Debug.Log(www.text);
        }
        return data;
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tianyongheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值