Составление потоков

Резервное хранилище — это устройство хранения информации, например диск или память. В каждом из резервных хранилищ используется собственный поток как реализация класса Stream. Каждый тип потока считывает и записывает байты в собственное резервное хранилище. Потоки, которые связаны с резервными хранилищами, называются базовыми. В конструкторах базовых потоков есть параметры, необходимые для присоединения потока к резервному хранилищу. Например, FileStream имеет конструктор, задающий путь, который определяет порядок совместного использования файла процессами и т. д.

Структура классов System.IO предоставляет упрощенное составление потоков. Базовые потоки могут быть присоединены к одному или нескольким сквозным потокам, которые обеспечивают требуемую функциональность. Модуль чтения или записи может быть присоединен к концу цепочки, что обеспечит легкое считывание или запись предпочитаемых типов.

В следующем примере кода создается поток FileStream для существующего файла MyFile.txt с целью буферизации файла MyFile.txt. (Обратите внимание, что экземпляры класса FileStreams буферизуются по умолчанию.) Затем создается StreamReader для чтения знаков из FileStream, который передается в StreamReader в качестве аргумента его конструктора. Метод ReadLine считывает до тех пор, пока Peek не перестает находить знаки.

Imports System
Imports System.IO

Public Class CompBuf
    Private Const FILE_NAME As String = "MyFile.txt"

    Public Shared Sub Main()
        If Not File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} does not exist!", FILE_NAME)
            Return
        End If
        Dim fsIn As new FileStream(FILE_NAME, FileMode.Open, _
            FileAccess.Read, FileShare.Read)
        ' Create an instance of StreamReader that can read
        ' characters from the FileStream.
        Using sr As New StreamReader(fsIn)
            Dim input As String
            ' While not at the end of the file, read lines from the file.
            While sr.Peek() > -1
                input = sr.ReadLine()
                Console.WriteLine(input)
            End While
        End Using
    End Sub
End Class
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);
            }
        }
    }
}
using namespace System;
using namespace System::IO;

public ref class CompBuf
{
private:
    static 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 = gcnew FileStream(FILE_NAME, FileMode::Open,
            FileAccess::Read, FileShare::Read);
        // Create an instance of StreamReader that can read
        // characters from the FileStream.
        StreamReader^ sr = gcnew 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);
        }
        sr->Close();
    }
};

int main()
{
    CompBuf::Main();
}

В следующем примере кода создается поток FileStream для существующего файла MyFile.txt с целью буферизации файла MyFile.txt. (Обратите внимание, что экземпляры класса FileStreams буферизуются по умолчанию.) Затем создается BinaryReader для чтения байтов из FileStream, который передается в StreamReader в качестве аргумента его конструктора. Метод ReadByte считывает до тех пор, пока PeekChar не перестает находить байты.

Imports System
Imports System.IO

Public Class ReadBuf
    Private Const FILE_NAME As String = "MyFile.txt"

    Public Shared Sub Main()
        If Not File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} does not exist.", FILE_NAME)
            Return
        End If
        Dim f As New FileStream(FILE_NAME, FileMode.Open, _
            FileAccess.Read, FileShare.Read)
        ' Create an instance of BinaryReader that can
        ' read bytes from the FileStream.
        Using br As new BinaryReader(f)
            Dim input As Byte
            ' While not at the end of the file, read lines from the file.
            While br.PeekChar() > -1
                input = br.ReadByte()
                Console.WriteLine (input)
            End While
        End Using
    End Sub
End Class
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 namespace System;
using namespace System::IO;

public ref class ReadBuf
{
private:
    static 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 = gcnew FileStream(FILE_NAME, FileMode::Open,
            FileAccess::Read, FileShare::Read);
        // Create an instance of BinaryReader that can
        // read bytes from the FileStream.
        BinaryReader^ br = gcnew 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);
        }
        br->Close();
    }
};

int main()
{
    ReadBuf::Main();
}

См. также

Ссылки

StreamReader

StreamReader.ReadLine

StreamReader.Peek

FileStream

BinaryReader

BinaryReader.ReadByte

BinaryReader.PeekChar

Основные понятия

Основы файлового ввода-вывода

Создание класса Writer