搜狗站长平台,杭州产品推广服务公司,海外市场推广策略,室内设计方案讲解思路首先StreamReader类的构造参数非常丰富 在这里#xff0c;我觉得最常用的就是StreamReader(Stream stream)和StreamReader#xff08;String str#xff09;这两个最常用 第一个可以直接放入一个数据流#xff0c;例如FileStream#xff0c;而第二个更简单直接放入str例如… 首先StreamReader类的构造参数非常丰富 在这里我觉得最常用的就是StreamReader(Stream stream)和StreamReaderString str这两个最常用 第一个可以直接放入一个数据流例如FileStream而第二个更简单直接放入str例如“c:/test.txt” 重点讲的是它的三个方法的使用 1.ReadLine 当遇到\n \r 或者是\r\n的时候 此方法返回这前面的字符串然后内部的指针往后移一位下次从新的地方开始读 知道遇到数据的结尾处返回null 所以经常这样使用 String content; try { StreamReader sr new StreamReader(test.txt); contentsr.ReadLine(); while(null ! content) { Debug.WriteLine(content); contentsr.ReadLine(); } sr.Close(); } catch(IOException e) { Debug.WriteLine(e.ToString()); } 2.Read() 此方法每次读取一个字符返回的是代表这个字符的一个正数当独到文件末尾时返回的是-1。 修改上面的使用 try { StreamReader sr new StreamReader(test.txt); int contentsr.Read(); while(-1 ! content) { Debug.Write(Convert.ToChar(content)); contentsr.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[] buffernew char[128]; int indexsr.Read(buffer,0,128); while(index0) { String content new String(buffer,0,128); Debug.Write(content); indexsr.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()); } 转载于:https://www.cnblogs.com/zhangran/archive/2012/03/08/2386006.html