unity pc 端文件读取 streamingassets datapath io

unity steamingassets 经常用于存放配置文件 txt json等 但是再编辑器可以用file 进行加载 但是发布windows之后就不可使用了 

另外 有一个问题就是 如果存放的是json串txt  反json的时候是会报错的 但是使用绝对路径是正常的 显然 我们既然使用了streamingassets路径就是不想使用绝对路径  对于此 有一个方案就是将文件copy到永久路径persistentDataPath

                   

         这里还会有这样一个问题  我们再程序里对数据进行了修改 想更新 保存到文本 但是当使用json后吧字符串写入txt 会发现编码格式不对  不是想象中的中文串  经过研究,写入之前需要进行转码

关键点说完上代码,注释详细一看就懂的那种哈哈:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;
/// <summary>
/// 加载方式
/// </summary>
public enum LoadMode
{
    StreamingAssets,
    IO,
    Resources
}
public delegate void OnLoad(DownloadHandler handler);

/// <summary>
/// 文件加载器
/// </summary>
public class FileLoader : MonoBehaviour
{
    public LoadMode mode;

    private void Start()
    {
        
    }

    /// <summary>
    /// unitywebrequest 方式加载
    /// </summary>
    /// <param name="path"></param>
    /// <param name="onload"></param>
    /// <returns></returns>
    IEnumerator UnityWebRequestLoad(string path,OnLoad onload )
    {
        Debug.Log(path);
        UnityWebRequest requeset = UnityWebRequest.Get(Path.Combine(Application.streamingAssetsPath, path));
        yield return requeset.Send();
        if (requeset.isNetworkError || requeset.isHttpError)
        {
            Debug.Log(requeset.error);
        }
        else
        {
            if(onload != null)
            {
                onload.Invoke(requeset .downloadHandler);
            }
        }
    }
	
    /// <summary>
    /// 加载文件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="oneend"></param>
    public void LoadTextFile(string path,Action<string> onend)
    {
        switch (mode)
        {
            case LoadMode.StreamingAssets:
                string savepath = Path.Combine(Application.persistentDataPath, path);
                Debug.Log("加载自:" + savepath);
                if (!File .Exists (savepath))
                {
                    Debug.Log("拷贝:" + savepath);
                    path = Path.Combine(Application.streamingAssetsPath, path);
                    File.WriteAllText(savepath, File.ReadAllText(path));
                }
                StartCoroutine(UnityWebRequestLoad(savepath , handlwer =>
                {
                    if (onend != null)
                    {
                        onend.Invoke(handlwer.text);
                    }
                }));
                break;
            case LoadMode.IO:
                path = Path.Combine("fill://", path);
                if (!File.Exists(path))
                {
                    Debug.LogError("文件不存在:" + path);
                }else
                {
                    if (onend !=null)
                    {
                        onend.Invoke(File.ReadAllText(path));
                    }
                }
                break;
            case LoadMode.Resources:
                string msg = Resources.Load<TextAsset>(path.Split('.')[0]).text;
                if (onend != null)
                    onend.Invoke(msg);
                break;
            default:
                break;
        }
    }

    /// <summary>
    /// 加载图片
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="oneend"></param>
    public IEnumerator  LoadSpriteFile(string path, int width =100 , int high =100, Action<Sprite> onend=null)
    {
        switch (mode)
        {
            case LoadMode.StreamingAssets:
                string savepath = Path.Combine(Application.persistentDataPath, path);
                if (!File.Exists(savepath))
                {
                    Debug.Log("copy");
                    yield return UnityWebRequestLoad(path, hand =>
                    {
                        FileStream fsDes = File.Create(savepath);
                        fsDes.Write(hand.data, 0, hand.data.Length);
                        fsDes.Flush();
                        fsDes.Close();
                    });
                    yield return LoadSpriteFile(path, width, high, onend);
                    yield break;
                }
                StartCoroutine(UnityWebRequestLoad(savepath, handlwer =>
                {
                    if (onend != null)
                    {
                        onend.Invoke(GetSprite(handlwer.data));
                    }
                }));
                break;
            case LoadMode.IO:
                path = Path.Combine("fill://", path);
                if (!File.Exists(path))
                {
                    Debug.LogError("文件不存在:" + path);
                }
                else
                {
                    FileStream fileStream = new FileStream(path , FileMode.Open, FileAccess.Read);
                    //创建文件长度缓冲区
                    byte[] bytes = new byte[fileStream.Length];
                    //读取文件
                    fileStream.Read(bytes, 0, (int)fileStream.Length);
                    yield return null;
                    //释放文件读取流
                    fileStream.Close();
                    //释放本机屏幕资源
                    fileStream.Dispose();
                    fileStream = null;

                    if (onend != null)
                    {
                        onend.Invoke(GetSprite (bytes ,width ,high ));
                    }
                }
                break;
            case LoadMode.Resources:
                Sprite sp = Resources.Load<Sprite>(path.Split('.')[0]);
                if (onend != null)
                {
                    onend.Invoke(sp);
                }
                yield return null;
                break;
            default:
                break;
        }
    }

    private Sprite GetSprite(byte [] datas, int w = 100, int h = 100)
    {
        Debug.Log(w + "  " + h);
        //创建Texture
        int width = w;
        int height = h;
        Texture2D texture = new Texture2D(width, height);
        texture.LoadImage(datas);
        return  Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
    }
    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="path"></param>
    public void SaveFile(string path,string msg)
    {
        string savepath = Path.Combine(Application.persistentDataPath, path);
        Debug.Log("保存到:" + savepath);

        StreamWriter writer = new StreamWriter(savepath);
        //转码
        Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
        msg = reg.Replace(msg, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });

        writer.WriteLine(msg);
        writer.Close();
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值