文件及IO操作(三)

什么是流?

  • 文件的数据从存储介质到内存再到程序程序,以及这个反向的过程里数据仿佛在一个通道中流动,我们把这个通道成为流。

                           

  • 按照输入源的不同流分为文件流、内存流、网络流等。

System.IO为我们提供了一个抽象类Stream。它在基础序列数据源与应用程序之间架设起了流动的通道。

常见操作:
  • Read:读出流中的数据。
  • Write: 向数据源中写入数据。
  • Seek: 在流中定位。

BinaryReader 和 BinaryWrite类,以二进制格式操作数据

    下表描述BinaryReader类常用的一些方法:

  1. colse:关闭当前读者和相应的流
  2. Read:从下层流读取字符,并且增加流的当前位置

下表描述BinaryWriter类的一些常用方法:

Close

关闭当前BinaryWriter和下层的流

Seek

在当前流设置位置

Write

写值到当前流

Flush

清除当前writer的所有缓存,导致任何缓存的数据被写入到下层的设备中 

Stream类

Stream类是IO名称空间中最重要的类之一,它是派生FileStream、MemoryStream和BufferedStream等不同类的抽象类

MemoryStream类用于向内存(而不是磁盘)读写数据

  Read() ----读MemoryStream并装值写入缓冲区
  ReadByte() ----从MemoryStream读一个字节
  Write() ----从缓冲区向MemoryStream写值
  WriteByte() ----从缓冲区向MemoryStream写一个字节
  WriteTo() ----将此内存流的内容写入别一个内存流

BufferedStream类用于对缓冲区进行读/写,有两个构造函数

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         }
View Code

FileStream类

FileStream(文件流)是Stream派生出的子类,使用这个类我们可以建立文件与程序的通道,对文件进行二进制数据的读写

    • Stream类被用来从文本文件中读取和写入数据。
    • 它是一个抽象类,它支持读写自己到流。主要实现派生类FileStream
    • 如果文件的数据仅是文本,那么你可以使用StreamReader类和StreamWriter类来完成相应的读和写任务

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 }
View Code

例2:

 1  static void Main(string[] args)
 2         {
 3             List<string> li = new List<string>();
 4 
 5             Console.WriteLine("-------------二进制文件写入--------------------
");
 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 + "
";
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("-------------二进制文件读取--------------------
");
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         }
View Code

 

你写了一个程序,其中要对硬盘上的一个文件操作,FileStream fs = new FileStream(fileName)
这样就是建立了一个文件缓冲流,换句话的意思就是说你通过这条程序,计算机给了一块内存空间,但是呢这块内存
空间不是你想干什么就干涉么的,他是专门存fileName这个文件里面的内容的,内存空间的大小,和其他信息,简单地
操作时没有办法访问的。当你要从文件里面读取一个Int整数的时候,程序做的不仅仅是读取一个int型整数,他会把该
数据附近的一大块数据都读出来放在刚才的那块空间中,为什么这么做呢,因为CPU访问硬盘比访问内存慢多了,所以
一开始读出很多的数据,后面需要使用的时候直接使用读出来的,就防止了再次访问硬盘。
相应的,你要网文件里面写入数据,也是先存到这个内存里,等存的东西足够多了,或者过了足够的时间,系统一次性
把内容写入硬盘。

TextReader类

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     }
View Code

TextWrite类

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     }
View Code

 StreamReader 类

    1. StreamReader类从TextReader抽象类继承。
    2. 类TextReader表示一个读者,它可以读取一系列字符。

下表描述了StreamReader类的通用方法:

 
方法 描述

Close

关闭StreamReader类的对象和相应的流,并且释放与reader相关的任何系统资源

Peek 

返回下一个可用的字符但不消费它

Read 

从流中读取下一个字符或下一个字符集

ReadLine

从当前流读取一行字符,并且返回数据为字符串

Seek 

允许在文件内移动读/写位置到任何地方

StreamWriter 类

    1. StreamWriter类继承自TextWriter抽象类。
    2. TextWriter类表示一个writer,它可以写一系列字符

下表描述了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         }
View Code

 流的写入用完后一定要记得Flush(清缓冲)同时如果不用流的话,把相应的流Close(关闭)!

Flush的作用就是强制执行了一次把数据写出硬盘,这样,你写入的数据确实到了文件中,否则如果程序突然中断,你 
要写入的内容也许还没写到文件中,就造成了数据丢失。

原文地址:https://www.cnblogs.com/Dream-High/p/3396048.html