unity中四种读取txt文件的方法和一种写入txt方法

来源:互联网 发布:可惜没如果知乎 编辑:程序博客网 时间:2024/05/28 15:28
//注意:要读取的文件的编码类型要为utf-8,不然会出现中文乱码或者直接不显示,如果是其它编码方式可以把文件
//另保存为utf-8的格式




using UnityEngine;
using System.Collections;
using System.IO;//用法三的时候需要定义这个
using System.Text;//法二的时候需要使用定义这个


public class GUTexture : MonoBehaviour {
    GUIText m_GUIText;
    public TextAsset m_TextAsset;
    TextAsset m_TextAsset1;
    string m_Str;
    string m_FileName;
    string[] strs;
// Use this for initialization
void Start () {
        m_GUIText = gameObject.GetComponent<GUIText>();
        m_FileName = "Z800虚拟头盔说明书链接UTF-8.txt";
}

// Update is called once per frame
void Update () {

}
    void OnMouseEnter() {
        //m_GUIText.text = m_Str;
       // ReadFile(m_FileName);//法二
        //m_GUIText.text =m_Str;//把读取到的内容放到GUIText组件中显示
       // Read();//法三
        m_GUIText.text = Resources.Load<TextAsset>("Z800虚拟头盔说明书链接").text;//法一
     


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

 






   

//方法三: 下面这个是通过io来读取txt文件的方法
  /*  public void Read()
    {
        try
        {


            string pathSource = m_FileName;


            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);  
                m_Str= UTF8Encoding.UTF8.GetString(bytes);
            }
        }
        catch
        {
            //ioEx.Message  
        }
    }  
   

   */






/* 法四

   using System.IO;
  using System.Text;


   Debug.Log(File.ReadAllText("C:\\Users\\zxy\\Desktop\\Z800虚拟头盔说明书链接.txt", Encoding.Default));  //ReadAllText方法第一个参数是要读取txt文件的路径,第二个参数

                                                                                                                                                                                               //第二个参数是编码方式,这里采用默认

*/       





/*一种以追加的方式写入txt方法

using System.IO;
using System.Text;

 File.AppendAllText("C:\\Users\\zxy\\Desktop\\Z800虚拟头盔说明书链接.txt", "我被写进来了",Encoding.Default);

//第一个参数是要写入的文件路径,第二个参数是要写入的文本,第三个参数是编码方式

*/

   
}