StreamReader 的ReadLine,Read,ReadToEnd方法

1.ReadLine()
当遇到 或者是 的时候 此方法返回这前面的字符串,然后内部的指针往后移一位下次从新的地方开始读,直到遇到数据的结尾处返回null,所以经常这样使用
       String content;
using(StreamReader sr = new StreamReader("test.txt"))
{
content=sr.ReadLine();
while(null != content)
{
  content=sr.ReadLine();
}
  sr.Close();
 
}
 
2.ReadToEnd()
这个方法适用于小文件的读取,一次性的返回整个文件, 这似乎非常容易和方便,但必须小心。将所有的数据读取到字符串对象中,会迫使文件中的数据放到内存中。应根据数据文件的大小禁止这样处理。如果数据文件非常大,最好将数据留在文件中,并使用StreamReader的方法访问文件。
上文修改如下:
try
{
  StreamReader sr = new StreamReader("test.txt");
  String content = sr.ReadToEnd();
  Debug.WriteLine();
  sr.Close();
}
catch(IOException e)
{
  Debug.WriteLine(e.ToString());
}
 
 
3  Read()
此方法每次读取一个字符,返回的是代表这个字符的一个正数,当独到文件末尾时返回的是-1
try
{
StreamReader sr = new StreamReader("test.txt");
int content=sr.Read();
while(-1 != content)
{
Debug.Write(Convert.ToChar(content));
content=sr.Read();
}
sr.Close();
}
catch(IOException e)
{
Debug.WriteLine(e.ToString());
}
 
此处需要补充一点,Read()还有一个使用方法

int Read(char[] buffer,int index,int count);

//补充一下,假设制定每次读128个字符,当文件内容小于128时,它会再循环一遍,从头开始读,直到读够128个字符

从文件流的第index个位置开始读,到count个字符,把它们存到buffer中,然后返回一个正数,内部指针后移一位,保证下次从新的位置开始读。
举个使用的例子:

try
{
StreamReader sr = new StreamReader("test.txt");
char[] buffer=new char[128];
int index=sr.Read(buffer,0,128);
while(index>0)
{
String content = new String(buffer,0,128);
Debug.Write(content);
index=sr.Read(buffer,0,128);
}
sr.Close();
}
catch(IOException e)
{
Debug.WriteLine(e.ToString());
}
 
原文链接: http://blog.csdn.net/kaituozhe345/article/details/7334988
原文地址:https://www.cnblogs.com/enamorbreeze/p/8558480.html