编写流

编写流

备份存储区是一个存储媒介,例如磁盘或内存。 每个不同的备份存储区都实现其自己的流作为 Stream 类的实现。 每个流类型也都从其给定的备份存储区读取字节并向其给定的备份存储区写入字节。 连接到备份存储区的流叫做基流。 基流具有的构造函数具有将流连接到备份存储区所需的参数。 例如,FileStream 具有指定路径参数(指定进程将如何共享文件的参数)等的构造函数。

System.IO 类的设计提供简化的流构成。 可以将基流附加到一个或多个提供所需功能的传递流。 读取器或编写器可以附加到链的末端,这样便可以方便地读取或写入所需的类型。

下面的代码示例围绕现有 MyFile.txt 创建 FileStream,为 MyFile.txt 提供缓冲。 (请注意,默认情况下缓冲 FileStreams。)然后,创建 StreamReader 以读取 FileStream 中的字符,FileStream 将作为 StreamReader 的构造函数参数传递给它。 ReadLine 将进行读取,直到 Peek 再也找不到任何字符为止。

using System;
using System.IO;

public class CompBuf
{
    private const string FILE_NAME = "MyFile.txt";

    public static void Main()
    {
        if (!File.Exists(FILE_NAME))
        {
            Console.WriteLine("{0} does not exist!", FILE_NAME);
            return;
        }
        FileStream fsIn = new FileStream(FILE_NAME, FileMode.Open,
            FileAccess.Read, FileShare.Read);
        // Create an instance of StreamReader that can read
        // characters from the FileStream.
        using (StreamReader sr = new StreamReader(fsIn))
        {
            string input;
            // While not at the end of the file, read lines from the file.
            while (sr.Peek() > -1)
            {
                input = sr.ReadLine();
                Console.WriteLine(input);
            }
        }
    }
}


下面的代码示例围绕现有 MyFile.txt 创建 FileStream,为 MyFile.txt 提供缓冲。 (请注意,默认情况下缓冲 FileStreams。)然后,创建 BinaryReader 以读取 FileStream 中的字节,FileStream 将作为 BinaryReader 的构造函数参数传递给它。 ReadByte 将进行读取,直到 PeekChar 再也找不到任何字节为止。

using System;
using System.IO;

public class ReadBuf
{
    private const string FILE_NAME = "MyFile.txt";

    public static void Main()
    {
        if (!File.Exists(FILE_NAME))
        {
            Console.WriteLine("{0} does not exist.", FILE_NAME);
            return;
        }
        FileStream f = new FileStream(FILE_NAME, FileMode.Open,
            FileAccess.Read, FileShare.Read);
        // Create an instance of BinaryReader that can
        // read bytes from the FileStream.
        using (BinaryReader br = new BinaryReader(f))
        {
            byte input;
            // While not at the end of the file, read lines from the file.
            while (br.PeekChar() > -1 )
            {
                input = br.ReadByte();
                Console.WriteLine(input);
            }
        }
    }
}
 

创建编写器

下面的代码示例创建了一个编写器,编写器是一个可以获取某些类型的数据并将其转换成可传递到流的字节数组的类。

using System;
using System.IO;

public class MyWriter
{
    private Stream s;

    public MyWriter(Stream stream)
    {
        s = stream;
    }

    public void WriteDouble(double myData)
    {
        byte[] b = BitConverter.GetBytes(myData);
        // GetBytes is a binary representation of a double data type.
        s.Write(b, 0, b.Length);
    }

    public void Close()
    {
        s.Close();
    }
}

在本示例中,您创建了一个具有构造函数的类,该构造函数带有流参数。 从这里,您可以公开任何需要的 Write 方法。 您必须将编写的所有内容都转换为 byte[]。 在您获得 byte[] 之后,Write 方法将其写入流 s

 
posted @ 2017-02-10 16:32  绣春刀  阅读(207)  评论(0编辑  收藏  举报