Compondo fluxos

Um armazenamento de backup é um meio de armazenamento, como um disco ou memória. Cada armazenamento de backup diferente implementa seu próprio fluxo como uma implementação da classe Stream. Cada tipo de fluxo lê e grava bytes de e para seu armazenamento de backup específico. Fluxos que se conectam aos armazenamentos de backup são chamados fluxos base. Fluxos base têm construtores que possuem os parâmetros necessários para conectar o fluxo ao armazenamento de backup. Por exemplo, FileStream tem construtores que especificam um parâmetro de caminho, que especifica como o arquivo será compartilhado por processos e assim por diante.

O design das classes System.IO fornece composição de fluxo simplificada. Fluxos base podem ser anexados a um ou mais fluxos de passagem que fornecem a funcionalidade desejada. Um leitor ou gravador pode ser anexado ao final da cadeia para que os tipos preferenciais possam ser lidos ou gravados facilmente.

O exemplo de código a seguir cria um FileStream ao redor do MyFile.txt existente para armazenar MyFile.txt em buffer. (Observe que FileStreams são armazenados em buffer por padrão.) Em seguida, um StreamReader é criado para ler caracteres da FileStream, que é passado para o StreamReader como seu argumento do construtor. ReadLinelê até Peek encontra-se não há mais caracteres.

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

O exemplo de código a seguir cria um FileStream ao redor do MyFile.txt existente para armazenar MyFile.txt em buffer. (Observe que FileStreams são armazenados em buffer por padrão.) Avançar, uma BinaryReader é criado para ler os bytes da FileStream, que é passado para o BinaryReader como seu argumento do construtor. ReadBytelê até PeekChar localiza nenhum mais bytes.

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

Consulte também

Referência

StreamReader

StreamReader.ReadLine

StreamReader.Peek

FileStream

BinaryReader

BinaryReader.ReadByte

BinaryReader.PeekChar

Conceitos

Arquivo básico de E/S

Criando um gravador