C#读写txt文件的两种方法

using UnityEngine;
using System.IO;
using System.Text;


public class ReadTxt : MonoBehaviour {

    
    //读取TXT方法一
    //使用FileStream类进行文件的都需,并将他转换成char数组,然后输出
    byte[] byData = new byte[100];
    char[] charData = new char[1000];
    public void ReadFun1()
    {

        FileStream file = new FileStream("C:\\Users\\123\\Desktop\\unity.txt", FileMode.Open);
        file.Seek(0, SeekOrigin.Begin);
        file.Read(byData, 0, 100);  //byData传进来的字节数组,用以接受FileStream对象中的数据,
                                    //第二个参数时字节数组中开始写入数据的位置,它通常时0,表示从数组的开端晚间中想数组写数据,最后一个参数规定从文件读多少字符
        Decoder d = Encoding.Default.GetDecoder();
        d.GetChars(byData, 0, byData.Length, charData, 0);
        Debug.Log(charData);
        foreach (char item in charData)
        {
            Debug.Log(item);
        }
        file.Close();

    }

    //读取TXT方法二
    //使用StreamReader读取文件,然后一行一行的输出
    public void ReadFun2(string path)
    {
        StreamReader sr = new StreamReader(path, Encoding.Default);
        string line;
        while ((line=sr.ReadLine())!=null)
        {
            Debug.Log(line.ToString());
        }
    }

    //文件的写入方法一
    //使用FileStream类创建文件,然后将数据写入到文件里。
    public void WriteFun1()
    {
        FileStream fs = new FileStream("C:\\Users\\123\\Desktop\\unity2.txt",FileMode.Create);
        //获得字节数组
        byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!");
        //开始写入
        fs.Write(data, 0, data.Length);
        //清空缓冲区,关闭流
        fs.Flush();
        fs.Close();
    }

    //文件的写入方法二
    public void WriteFun2(string path)
    {
        FileStream fs = new FileStream(path,FileMode.Create);
        StreamWriter sw = new StreamWriter(fs);
        //开始写入
        sw.Write("这是用代码创建的第二个TXT");
        sw.Close();
        fs.Close();

    }


    private void Start()
    {
        //ReadFun1();
        //ReadFun2("C:\\Users\\123\\Desktop\\unity.txt");
        //WriteFun1();
        WriteFun2("C:\\Users\\123\\Desktop\\unity3.txt");
    }

}

读和写各两种方法,请注意路径是否正确

  




猜你喜欢

转载自blog.csdn.net/roadlun/article/details/80443289