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());
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM