注:TextReader()和StreamReader()是父子关系
一、TextReader()
那么TextReader()中都有哪些主要的方法呢:
1:具有一个protected类型的构造函数
2: void Close()方法:
TextReader也有Close方法,切记,在用完之后应该主动关闭它
3: void Dispose()方法:
释放所有该TextReader 所持有的所有资源(注意,假如TextReader中持有stream或其他对象,当TextReader执行了Dispose方法时,stream对象也被回收了)
4:int Peek()方法
这个方法主要是寻找当前char的下个 char,当返回值是-1时,表示下个 char已经是最后一个位置的char了
5:int Read()方法:
同样,read()方法是读取下一个char, 但是和peek方法不同,read()方法使指针指向下个字符,但是peek还是指向原来那个字符
6:int Read(Char[] buffer,int index,int count)方法:
这个重载read方法和上一章Stream的read方法有点神似,区别是一个参数是byte数组,而这个是char数组,
(注意:是通过reader 将数据数据读入buffer数组),index:从哪个位置开始,count:读取char数量
7: int ReadBlock(Char[] buffer,int index,int count)方法:
和Read方法基本一致,区别是从效率上来说ReadBlock更高点,而且ReadBlock并非属于线程安全,使用时要注意
8:virtual string ReadLine() 方法:
顾名思义,这个方法将读取每一行的数据并返回当前行的字符的字符串
9:virtual string ReadToEnd()方法:
包含从当前位置到 TextReader 的结尾的所有字符的字符串
下面使用了ReadLine()方法输出一行,其他的就自己动手试试吧。
using System.IO;
using UnityEngine;
public class StreamReadAndWrite : MonoBehaviour
{
private string textPath;
void Start ()
{
textPath = Application.dataPath + @"\TestFile.txt";
TextReaderText();
}
void TextReaderText()
{
using (TextReader textReader = new StreamReader(textPath))
{
while (true)
{
string str = textReader.ReadLine();
if (string.IsNullOrEmpty(str))
break;
else
Debug.Log(str);
}
textReader.Close();
}
}
}
二、StreamReader()
学习StreamReader()可以对照上面的TextReaber(),他们可是父子关系,子类继承了父类。