StreamReader 的ReadLine,Read,ReadToEnd方法


1.ReadLine()
當遇到\n \r 或者是\r\n的時候 此方法返回這前面的字符串,然后內部的指針往后移一位下次從新的地方開始讀,直到遇到數據的結尾處返回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


免責聲明!

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



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