url: http://www.cnblogs.com/zhxhdean/archive/2012/02/20/2359605.html
StreamReader,StreamWriter,StringReader,StringWriter每次看到这几个词的时候,就会混淆(理解不够深刻),在使用过程中也经常犯浑,为了能更好的理解,写下此文章。
正文
概念
首先,从字面可以看出,StreamReader,StringReader是用来读操作,StreamWriter,StringWriter是用来写操作。
接下来看这几个类在类库中的层次
上图中,StreamReader,StringReader都派生自TextReader类(TextReader:表示可读取连续字符序列的读取器。抽象基类)
StreamReader从流中读取字符
StringReader从字符串读取字符
上图中,StreamWriter,StringWriter派生自TextWriter类(TextWriter:表示可以编写一个有序字符序列的编写器。该类为抽象类。)
StreamWriter将字符写入流
StringWriter将字符写入字符串
代码
reader操作
private static void StringRead() { string in_str ="流操作,字符操作,io操作"; string read_str, aParagraph = null; StringReader sr = new StringReader(in_str); while (true) { read_str = sr.ReadLine(); if (read_str != null) { aParagraph = aParagraph + in_str + " "; } else { aParagraph = aParagraph + "\n"; break; } } }
private static void StreamRead() { Stream rStream = new FileStream(@"E:/20120214.txt", FileMode.Open); StreamReader sr = new StreamReader(rStream, Encoding.UTF8); //从流中读取字符 string result = sr.ReadToEnd(); //释放资源 sr.Close(); rStream.Close(); }
writer操作
private static void StreamWriter() { string in_str = DateTime.Now.ToString("MM-dd HH:mm:ss:fff"); //第二个参数 是否追加 StreamWriter sw = new StreamWriter(@"E:/20120214.txt",true,Encoding.Default); sw.Write(in_str); sw.Flush(); sw.Close(); } private static void StringWriter() { StringWriter sw = new StringWriter(); sw.Write("文字,学习,文字,c#"); sw.Close(); }
StreamReader,StreamWriter,StringReader,StringWriter每次看到这几个词的时候,就会混淆(理解不够深刻),在使用过程中也经常犯浑,为了能更好的理解,写下此文章。
正文
概念
首先,从字面可以看出,StreamReader,StringReader是用来读操作,StreamWriter,StringWriter是用来写操作。
接下来看这几个类在类库中的层次
上图中,StreamReader,StringReader都派生自TextReader类(TextReader:表示可读取连续字符序列的读取器。抽象基类)
StreamReader从流中读取字符
StringReader从字符串读取字符
上图中,StreamWriter,StringWriter派生自TextWriter类(TextWriter:表示可以编写一个有序字符序列的编写器。该类为抽象类。)
StreamWriter将字符写入流
StringWriter将字符写入字符串
代码
reader操作
private static void StringRead() { string in_str ="流操作,字符操作,io操作"; string read_str, aParagraph = null; StringReader sr = new StringReader(in_str); while (true) { read_str = sr.ReadLine(); if (read_str != null) { aParagraph = aParagraph + in_str + " "; } else { aParagraph = aParagraph + "\n"; break; } } }
private static void StreamRead() { Stream rStream = new FileStream(@"E:/20120214.txt", FileMode.Open); StreamReader sr = new StreamReader(rStream, Encoding.UTF8); //从流中读取字符 string result = sr.ReadToEnd(); //释放资源 sr.Close(); rStream.Close(); }
writer操作
private static void StreamWriter() { string in_str = DateTime.Now.ToString("MM-dd HH:mm:ss:fff"); //第二个参数 是否追加 StreamWriter sw = new StreamWriter(@"E:/20120214.txt",true,Encoding.Default); sw.Write(in_str); sw.Flush(); sw.Close(); } private static void StringWriter() { StringWriter sw = new StringWriter(); sw.Write("文字,学习,文字,c#"); sw.Close(); }
|
请发表评论