StreamReader类以及其方法ReadLine,Read,ReadToEnd的分析

首先StreamReader类的构造参数非常丰富
在这里,我觉得最常用的就是StreamReader(Stream stream)和StreamReader(String str)这两个最常用
第一个可以直接放入一个数据流,例如FileStream,而第二个更简单直接放入str例如“c:/test.txt”
重点讲的是它的三个方法的使用
1.ReadLine()
当遇到\n \r 或者是\r\n的时候 此方法返回这前面的字符串,然后内部的指针往后移一位下次从新的地方开始读
知道遇到数据的结尾处返回null
所以经常这样使用
String content;
try
{
StreamReader sr = new StreamReader("test.txt");
content=sr.ReadLine();
while(null != content)
{
Debug.WriteLine(content);
content=sr.ReadLine();
}
sr.Close();
}
catch(IOException e)
{
Debug.WriteLine(e.ToString());
}
2.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);
从文件流的第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());
}
3.ReadToEnd()
这个方法适用于小文件的读取,一次性的返回整个文件
上文修改如下:
try
{
StreamReader sr = new StreamReader("test.txt");
String content = sr.ReadToEnd();
Debug.WriteLine();
sr.Close();
}
catch(IOException e)
{
Debug.WriteLine(e.ToString());
}
posted @ 2012-03-08 23:45  张小然  阅读(16124)  评论(1编辑  收藏  举报