Unity动态读取文本文件的几种方式

【前言】

最近用AVProVideo做视频程序时,把AVProVideo加载视频的方式,改成用配置文件来加载,本地配置的话,做了几个版本,其中一个版本就涉及到读取文本文件,因为只加载视频名称,不需要做键值对,所以就没用json来做这个事情。
在这里插入图片描述

配图:OnGUI视图,第1种写入,后4中加载文本内容

【思路分析】

1.Start里面检测目录,然后创建streamingAssets目录

2.OnGUI处理对文本的操作

  • 方法一:创建文本并写入
  • 方法二:ReadAllText方法读取txt文件
  • 方法三:UnityWebRequest加载文本内容
  • 方法四:通过File.ReadAllLines(m_FilePath);自定义方法来读取
  • 方法五:通过FileStream来读取txt文件
    直接放出代码,自行看代码里的注释和OnGUI打印吧

【放出代码】


using UnityEngine;
using System.Collections;
using System.IO;
using System.Text;
using UnityEngine.Networking;
using System;

public class ReadTxt : MonoBehaviour
{
    
    
    [SerializeField] TextAsset m_TextAsset;//这个需要在unity编辑器进行赋值,把.txt文本文件保存在Asset下的,TextAsset.text方式比较简单,就不多介绍了
    string m_FilePath;
    string path;

    void Start()
    {
    
    
        path = Application.streamingAssetsPath + "/TextAsset";
        m_FilePath = path + "/我是个可怜的文本.txt";//文本路径
        //if((File.Exists(m_FilePath))== false)
        //{
    
    
        //    print("创建streamingAssetsPath目录");
        //    File.Create(m_FilePath);
        //}

        if (Directory.Exists(path) == false)
        {
    
    
            Directory.CreateDirectory(path);
            print("streamingAssets创建成功");
        }
    }


    public Texture buttonTexture;
    private string info = "一般读直接创建写入然后读取,直接用1写入,后用2就轻松实现读取";
    void OnGUI()
    {
    
    
        GUI.BeginGroup(new Rect(0, 0, 100 * 10, 100 * 5));
        GUI.Box(new Rect(0, 0, 100 * 10, 100 * 10), "几种常见的加载文本方式");        

        // 第1个文字按钮
        GUI.color = Color.yellow;  //按钮文字颜色  
        GUI.backgroundColor = Color.red; //按钮背景颜色

        if (GUI.Button(new Rect(50, 50, 150, 50), "方法一"))
        {
    
                            
            info = "创建文本并写入\n API:public static void AppendAllText(string path, string contents, Encoding encoding);";
            Debug.Log(info);            
            File.AppendAllText(m_FilePath, "我被写进来了", Encoding.UTF8); //第一个参数是要写入的文件路径,第二个参数是要写入的文本,第三个参数是编码方式           
        }

        // 第2个图片按钮
        GUI.color = Color.white;  //按钮文字颜色  
        GUI.backgroundColor = Color.green; //按钮背景颜色
        if (GUI.Button(new Rect(50, 50 * 2, 150, 50), "方法二"))
        {
    
                
            info = "ReadAllText方法读取txt文件\n API: public static string ReadAllText(string path, Encoding encoding);";
            Debug.Log("方法2==" + File.ReadAllText(m_FilePath, Encoding.UTF8));//ReadAllText方法第一个参数是要读取txt文件的路径,第二个参数是编码方式,这里采用默认
        }

        // 第3个图片按钮
        GUI.color = Color.white;  //按钮文字颜色  
        GUI.backgroundColor = Color.green; //按钮背景颜色
        if (GUI.Button(new Rect(50, 50 * 3, 150, 50), "方法三"))
        {
    
    
            info = "UnityWebRequest加载文本内容\n API: UnityWebRequest.downloadHandler.text";
            StartCoroutine(UnityWebRequestLoad(m_FilePath, unityWebRequestcallback));
        }

        // 第4个图片按钮
        GUI.color = Color.white;  //按钮文字颜色  
        GUI.backgroundColor = Color.green; //按钮背景颜色
        if (GUI.Button(new Rect(50, 50 * 4, 150, 50), "方法四"))
        {
    
    
            info = "通过File.ReadAllLines(m_FilePath);自定义方法来读取";
            Debug.Log(ReadFile());
        }

        // 第5个图片按钮
        GUI.color = Color.white;  //按钮文字颜色  
        GUI.backgroundColor = Color.green; //按钮背景颜色
        if (GUI.Button(new Rect(50, 50 * 5, 150, 50), "方法五"))
        {
    
    
            info = "通过FileStream来读取txt文件";
            Debug.Log(Read());
        }        

        GUI.Box(new Rect(250, 50, 100 * 5, 100 * 3), buttonTexture);
        GUI.Label(new Rect(300, 100, 100 * 4, 100 * 2), info);
        GUI.EndGroup();
    }

    /// <summary>通过ReadFile(名字自己定义)方法来读取,传入的是文件路径</summary>
    string ReadFile()
    {
    
    
        string m_Str = null;
        string[] strs = File.ReadAllLines(m_FilePath);//读取文件的所有行,并将数据读取到定义好的字符数组strs中,一行存一个单元
        for (int i = 0; i < strs.Length; i++)
        {
    
    
            m_Str += strs[i];//读取每一行,并连起来
            m_Str += "\n";//每一行末尾换行
        }
        return m_Str;
    }

    /// <summary>下面这个是通过文件流来读取txt文件的方法</summary>
    string Read()
    {
    
    
        try
        {
    
    
            string pathSource = m_FilePath;
            using (FileStream fsSource = new FileStream(pathSource,
                        FileMode.Open, FileAccess.Read))
            {
    
    
                //Read the source file into a byte array.  
                byte[] bytes = new byte[fsSource.Length];
                int numBytesToRead = (int)fsSource.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
    
    
                    int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

                    if (n == 0)
                        break;
                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
                //text = Encoding.Default.GetString(bytes);
                return UTF8Encoding.UTF8.GetString(bytes);
            }
        }
        catch (System.Exception ex)
        {
    
    
            Debug.LogError("方法Read()异常" + ex);
        }
        return null;
    }

    /// <summary>
    /// UnityWebRequest加载文本内容
    /// </summary>
    /// <param name="url">加载路径</param>
    /// <param name="callback">加载后处理文本的回调函数</param>
    /// <returns></returns>
    public static IEnumerator UnityWebRequestLoad(string url, Action<UnityWebRequest> callback)
    {
    
    
        UnityWebRequest webRequest = UnityWebRequest.Get(url);
        yield return webRequest.SendWebRequest();
        if (webRequest.isNetworkError || webRequest.isHttpError)
        {
    
    
            Debug.Log(webRequest.error);
        }
        else
        {
    
    
            callback.Invoke(webRequest);
            yield return null;
        }
    }

    /// <summary>
    /// UnityWebRequest回调函数
    /// </summary>
    /// <param name="obj"></param>
    private void unityWebRequestcallback(object obj)
    {
    
    
        UnityWebRequest request = obj as UnityWebRequest;
        print(request.downloadHandler.text);
        request.Dispose();
    }

    //IEnumerator LoadFile()
    //{
    
    
    //    UnityWebRequest request = UnityWebRequest.Get(@"E:\UnityProjects\TestFile\TestFile.txt");
    //    yield return request.SendWebRequest();
    //    if (request.isHttpError || request.isNetworkError)
    //    {
    
    
    //        Debug.Log(request.error);
    //    }
    //    else
    //    {
    
    
    //        ShowText.text = request.downloadHandler.text;
    //    }
    //}
}

【最后想说】

如果想对文本进行读写,最快捷的是方法一和方法二,在下一篇我将更新如何在AVPro修改的视频模板在打包的本地文件替换播放,创作不易,很多功夫都花去写代码测试了,文章中的败笔之处多多包涵。

猜你喜欢

转载自blog.csdn.net/qq_42541751/article/details/115187602