什么是流?html
System.IO为咱们提供了一个抽象类Stream。它在基础序列数据源与应用程序之间架设起了流动的通道。数组
下表描述BinaryReader类经常使用的一些方法:缓存
下表描述BinaryWriter类的一些经常使用方法:网络
Closeide |
关闭当前BinaryWriter和下层的流函数 |
Seek编码 |
在当前流设置位置spa |
Write3d |
写值到当前流code |
Flush |
清除当前writer的全部缓存,致使任何缓存的数据被写入到下层的设备中 |
Stream类是IO名称空间中最重要的类之一,它是派生FileStream、MemoryStream和BufferedStream等不一样类的抽象类
Read() ----读MemoryStream并装值写入缓冲区
ReadByte() ----从MemoryStream读一个字节
Write() ----从缓冲区向MemoryStream写值
WriteByte() ----从缓冲区向MemoryStream写一个字节
WriteTo() ----将此内存流的内容写入别一个内存流
public BufferedStream(Stream stName);
public BufferedStream(Stream stName, int bsize); // bsize表示缓冲区大小
1 static void Main(string[] args) 2 { 3 MemoryStream memStr = new MemoryStream(); 4 BufferedStream buffStr = new BufferedStream(memStr); 5 buffStr.WriteByte((byte)100); 6 buffStr.Position = 0; //取得memStr的当前位置Positon属性为0,以便buffStr的当前位置设置为流的开始
7 byte[] arrb = { 1, 2, 3 }; 8 buffStr.Read(arrb, 0, 1); // 用流的当前位置的值填充字节数组arrb
9 for (int i = 0; i < 3; i++) 10 { 11 Console.WriteLine("这个值是{0}", arrb[i]); 12 } 13 Console.WriteLine("ReadByte()的返回值是{0}", buffStr.ReadByte()); // 返回-1表示流的末尾
14 Console.ReadKey(); 15 }
FileStream(文件流)是Stream派生出的子类,使用这个类咱们能够创建文件与程序的通道,对文件进行二进制数据的读写
FileStream 类用于对文件执行读/写操做,Read()和Write()方法用于读/写操做
FileStream类构造函数有许多重写形式,以方便建立该类的实例
FileStream(string FilePath,FileMode)
FileStream(stirng FilePath,FileMode,FileAccess)
FileStream(string FilePath,FileMode,FileAccess,FileShare)
FileMode为enum类型(建立或打开),其值以下:
Append:打开一个文件并查找到文件末尾,以便可以附加新的数据,若是文件不存在,则新建一个文件
Create:用指定名称新建一个文件,若是存在具备相同名称的文件,则覆盖旧文件
CreateNew:新建一个文件
Open:打开一个文件,指定文件必须存在
OpenOrCreate:与Open相似,只是指定文件不存在时,新建一个
Truncate:根据此枚举,打开指定文件并将之截断为0字节(大小为0字节),文件必须存在
FileAccess枚举值(读写权限):Read / Write / ReadWrite
FileShare枚举值(共享):
None:谢绝共享当前文件。文件关闭前,打开该文件的任何请求都将失败
Read:只能对文件进行读取操做
Write:能够对文件进行写入操做
ReadWrite:能够进行对文件的读写和写入两种操做
例1:
1 static void Main(string[] args) 2 { 3 4 5 //===============================写入================================ 6 //使用FileStream读写文件 7 string path = @"e:\1.txt"; 8 9 Console.WriteLine("输入你要写入的文件内容:"); 10 string info = Console.ReadLine(); 11 //建立文件流,对str文件写操做 12 FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); 13 //把输入的字符串解码成字节数组 14 byte[] array = new UTF8Encoding(true).GetBytes(info);//UTF8编码 15 16 //byte[] array = new ASCIIEncoding().GetBytes(info); 17 //写入 18 fs.Write(array, 0, array.Length); 19 20 21 fs.Flush();//清空缓存区 22 fs.Close();//关闭流 23 24 Console.WriteLine("写入成功"); 25 26 //===============================读取================================ 27 28 FileStream fs1 = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); 29 //定义数组用于接收读取的内容 30 byte[] arr = new byte[fs1.Length]; 31 //读取 32 fs1.Read(arr, 0, arr.Length); 33 34 fs1.Close();//关闭流 35 36 Console.WriteLine("读取到得内容以下:"); 37 Console.WriteLine(new UTF8Encoding(true).GetString(arr)); 38 }
例2:
1 static void Main(string[] args) 2 { 3 List<string> li = new List<string>(); 4 5 Console.WriteLine("-------------二进制文件写入--------------------\n"); 6 Console.WriteLine("请输入你的我的信息:"); 7 Console.Write("您的姓名:"); 8 li.Add(Console.ReadLine()); 9 Console.Write("你的年龄:"); 10 li.Add(Console.ReadLine()); 11 Console.Write("你的爱好:"); 12 li.Add(Console.ReadLine()); 13 Console.Write("你的说明:"); 14 li.Add(Console.ReadLine()); 15 16 string pathtxt = @"e:\10.text"; 17 string str = string.Empty; 18 19 FileStream sw = new FileStream(pathtxt, FileMode.Create, FileAccess.Write, FileShare.Write); 20 21 string str1 = ""; 22 foreach (string s in li) 23 { 24 str1 += s + "\r\n"; 25 } 26 byte[] b = UTF8Encoding.Default.GetBytes(str1); 27 sw.Write(b, 0, b.Length); 28 29 sw.Flush(); 30 sw.Close(); 31 32 Console.WriteLine("二进制文件写入成功!"); 33 Console.WriteLine("-------------二进制文件读取--------------------\n"); 34 Console.WriteLine("读取二进制文件"); 35 FileStream file = new FileStream(pathtxt, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); 36 37 byte[] a = new byte[file.Length]; 38 while ((file.Read(a, 0, a.Length)) > 0) 39 { 40 Console.Write(UTF8Encoding.Default.GetString(a)); 41 } 42 file.Flush(); 43 file.Close(); 44 }
你写了一个程序,其中要对硬盘上的一个文件操做,FileStream fs = new FileStream(fileName)
这样就是创建了一个文件缓冲流,换句话的意思就是说你经过这条程序,计算机给了一块内存空间,可是呢这块内存
空间不是你想干什么就干涉么的,他是专门存fileName这个文件里面的内容的,内存空间的大小,和其余信息,简单地
操做时没有办法访问的。当你要从文件里面读取一个Int整数的时候,程序作的不只仅是读取一个int型整数,他会把该
数据附近的一大块数据都读出来放在刚才的那块空间中,为何这么作呢,由于CPU访问硬盘比访问内存慢多了,因此
一开始读出不少的数据,后面须要使用的时候直接使用读出来的,就防止了再次访问硬盘。
相应的,你要网文件里面写入数据,也是先存到这个内存里,等存的东西足够多了,或者过了足够的时间,系统一次性
把内容写入硬盘。
TextReader类是StreamReader和StringReader类的抽象基类,可用于读取有序的字符序列
Read() 读取输入流中的下一个字符或下一组字符
ReadLine() 从当前流中读取一行字符并将数据做为字符串返回
ReadToEnd() 从流的当前位置到末尾读取流
1 class Program 2 { 3 static string ans = "y"; 4 static void Main(string[] args) 5 { 6 Console.WriteLine("1.读取文件"); 7 Console.WriteLine("2.读取字符串"); 8 try
9 { 10 Reading(); 11 } 12 catch (Exception ex) 13 { 14 Console.WriteLine(ex.Message); 15 Console.ReadKey(); 16 } 17 } 18 static void Reading() 19 { 20 if (ans == "Y" || ans == "y") 21 { 22 Console.Write("输入你的选择[1/2]:"); 23 int choice = Convert.ToInt32(Console.ReadLine()); 24 if (choice == 1) 25 { 26 Console.WriteLine("输入文件名:"); 27 string filename = Console.ReadLine(); 28 if (!File.Exists(filename)) 29 { 30 Console.WriteLine(filename + "不存在!"); 31 return; 32 } 33 StreamReader sr = File.OpenText(filename); 34 string input; 35 while ((input = sr.ReadLine()) != null) 36 { 37 Console.WriteLine(input); 38 } 39 Console.WriteLine("已达到流末尾。"); 40 sr.Close(); 41 Console.Write("要继续吗?[Y/N]:"); 42 ans = Console.ReadLine(); 43 Reading(); 44 } 45 else if (choice == 2) 46 { 47 Console.Write("输入字符串:"); 48 string str = Console.ReadLine(); 49 char[] b = new char[str.Length]; 50 StringReader sr = new StringReader(str); 51 sr.Read(b, 0, str.Length); 52 Console.WriteLine(b); 53 Console.WriteLine("要继续吗[Y/N]:"); 54 ans = Console.ReadLine(); 55 Reading(); 56 } 57 else
58 { 59 Console.WriteLine("输入1或2做为选择:"); 60 } 61 } 62 } 63 }
TextWrite类用于编写有序字符的类的抽象基类。StreamWriter和StringWriter类是TextWriter类的两个派生类
Write() 将数据写入流
WriteLine() 将数据写入流,并在结尾标记结束符
StringWriter类用于装数据写入字符串,与StreamWriter类相似,区别仅在于它是向字符串(而不是向流)写入
1 class Program 2 { 3 static string ans = "y"; 4 static void Main(string[] args) 5 { 6 Writing(); 7 } 8 static void Writing() 9 { 10 if (ans == "Y" || ans == "y") 11 { 12 Console.WriteLine("输入文件名:"); 13 string filename = Console.ReadLine(); 14 if (!File.Exists(filename)) 15 { 16 Console.WriteLine(filename + "不存在!"); 17 return; 18 } 19 StreamWriter sr = File.AppendText(filename); 20 Console.Write("输入要写入的字符串:"); 21 string str = Console.ReadLine(); 22 sr.WriteLine(str); 23 sr.Close(); 24 Console.Write("要继续吗?[Y/N]:"); 25 ans = Console.ReadLine(); 26 Writing(); 27 } 28 } 29 }
下表描述了StreamReader类的通用方法:
方法 | 描述 |
Close |
关闭StreamReader类的对象和相应的流,而且释放与reader相关的任何系统资源 |
Peek |
返回下一个可用的字符但不消费它 |
Read |
从流中读取下一个字符或下一个字符集 |
ReadLine |
从当前流读取一行字符,而且返回数据为字符串 |
Seek |
容许在文件内移动读/写位置到任何地方 |
StreamWriter 类
下表描述了StreamWriter类的一些经常使用的方法:
方法 | 描述 |
Close |
关闭当前StreamWriter的对象和相应的流 |
Flush |
清除当前writer的全部缓冲,致使任何缓冲的数据被写入相应的流 |
Write |
写入流 |
WriteLine |
经过覆盖参数写入指定数据,在行的最后 |
1 static void Main(string[] args) 2 { 3 string path = @"e:\1.txt"; 4 5 //建立写文本文件,并赞成追加 6 StreamWriter sw = new StreamWriter(path, true); 7 //逐行写入 8 sw.WriteLine("编号:"); 9 sw.WriteLine("姓名:"); 10 sw.WriteLine("性别:"); 11 sw.WriteLine("地址:"); 12 sw.WriteLine("电话:"); 13 sw.WriteLine(); 14 15 sw.Flush();//清除当前缓冲区 16 sw.Close();//关闭流 17 // Process.Start("notepad.exe", path);//打开记事本 18 19 //StreamReader和StreamWriter读取文本文件 20 StreamReader sr = new StreamReader(@"e:\1.txt", Encoding.UTF8); 21 22 string s = string.Empty; 23 while ((s = sr.ReadLine()) != null) 24 { 25 //string s = sr.ReadLine(); 26 Console.WriteLine(s); 27 } 28 }
流的写入用完后必定要记得Flush(清缓冲)同时若是不用流的话,把相应的流Close(关闭)!
Flush的做用就是强制执行了一次把数据写出硬盘,这样,你写入的数据确实到了文件中,不然若是程序忽然中断,你 要写入的内容也许还没写到文件中,就形成了数据丢失。