C#流(stream)

流用于对IO处理

在System.IO名称空间中有以下类

BinaryReader/Writer

TextReader/Writer

Stream

其中类Stream为抽象类。由此有三个派生类:

MemoryStream:对内存进行读取与写入

BufferedStream:对缓冲器进行读取/写入

FileStream:对文件执行读取与写入

TextReader/Writer为抽象类。由此派生类:

StreamReader/StreamWirter

StringReader/StreamWriter

需要引入命名空间:

using System.IO

内存流与缓冲的使用举例: 

MemoryStream memStream=new MemoryStream(); 

BufferedStream bufStream=new BufferedStream(memStream); 

byte[] b=new byte[10]; 

for(int i=0;i<10;i++) 

{ 

bufStream.WriteByte((byte)i); 

} 

bufStream.Position=0; 

bufStream.Read(b,0,9); 

for(int i=0;i<10;i++) 

{ 

Console.WriteLine("读的值是:{0}",b[i]); 

} 

Console.WriteLine("值是:{0}",bufStream.ReadByte()); 

Console.ReadLine(); 
文件流的使用 

string s=Console.ReadLine(); 

FileStream fileStream=new FileStream(s,FileMode.OpenOrCreate); 

BinaryWriter binStream=new BinaryWriter (fileStream); 

for(int i=1;i<=10;i++) 

{ 

binStream.Write((int)i); 

} 

binStream.Close(); 

fileStream.Close(); 

FileStream f=new FileStream(s,FileMode.Open,FileAccess.Read,FileShare.ReadWrite); 

BinaryReader buf=new BinaryReader(f); 

for(int i=1;i<10;i++) 

{ 


Console.WriteLine("输出{0}",buf.ReadByte ()); //在vs2012中这样不能读出东西来

Console.WriteLine("输出{0}",Bur.ReadInt32());才行,因为int是32位的

}
文本流的使用 

string fileName,s; 

fileName=Console.ReadLine(); 

StreamWriter fn=new StreamWriter(fileName,true); 

for(int i=1;i<10;i++) 

{ 

s=Console.ReadLine(); 

fn.WriteLine(s); 

} 

fn.Close(); 

StreamReader fr=new StreamReader(fileName); 


for(int i=1;i<10;i++) 

{ 

s=fr.ReadLine(); 

Console.WriteLine(s); 

} 

fr.Close(); 

Console.ReadLine(); 
字符串流的使用 

using System.Text; 

StringBuilder str=new StringBuilder(100,1000); 

StringWriter sw=new StringWriter(str); 

for(int i=1;i<5;i++) 

{ 

sw.Write(Console.ReadLine()); 

} 

sw.Close(); 

Console.WriteLine(sw.ToString()); 

StringReader sr=new StringReader(sw.ToString()); 

Console.WriteLine(sr.ReadLine()); 

Console.ReadLine();

 

posted @ 2013-02-15 22:10  louiskoo  阅读(41959)  评论(3编辑  收藏  举报