編寫流

編寫流

備份存儲區是一個存儲媒介,例如磁盤或內存。 每一個不一樣的備份存儲區都實現其本身的流做爲 Stream 類的實現。 每一個流類型也都從其給定的備份存儲區讀取字節並向其給定的備份存儲區寫入字節。 鏈接到備份存儲區的流叫作基流。 基流具備的構造函數具備將流鏈接到備份存儲區所需的參數。 例如,FileStream 具備指定路徑參數(指定進程將如何共享文件的參數)等的構造函數。數組

System.IO 類的設計提供簡化的流構成。 能夠將基流附加到一個或多個提供所需功能的傳遞流。 讀取器或編寫器能夠附加到鏈的末端,這樣即可以方便地讀取或寫入所需的類型。ide

下面的代碼示例圍繞現有 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 再也找不到任何字節爲止。ui

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);
            }
        }
    }
}
 

建立編寫器

下面的代碼示例建立了一個編寫器,編寫器是一個能夠獲取某些類型的數據並將其轉換成可傳遞到流的字節數組的類。this

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 方法將其寫入流 sspa

相關文章
相關標籤/搜索