StreamReader.Read 메서드

정의

입력 스트림에서 다음 문자 또는 다음 문자 집합을 읽습니다.

오버로드

Read()

입력 스트림에서 다음 문자를 읽고 문자 위치를 한 문자씩 앞으로 이동합니다.

Read(Span<Char>)

현재의 스트림에서 범위로 문자를 읽어 들입니다.

Read(Char[], Int32, Int32)

현재 스트림에서 지정된 최대 문자를 지정된 인덱스부터 버퍼로 읽어 들입니다.

Read()

Source:
StreamReader.cs
Source:
StreamReader.cs
Source:
StreamReader.cs

입력 스트림에서 다음 문자를 읽고 문자 위치를 한 문자씩 앞으로 이동합니다.

public:
 override int Read();
public override int Read ();
override this.Read : unit -> int
Public Overrides Function Read () As Integer

반환

Int32 개체로 표시되는 입력 스트림의 다음 문자이거나, 사용할 수 있는 문자가 더 이상 없는 경우에는 -1입니다.

예외

I/O 오류가 발생했습니다.

예제

다음 코드 예제에서는 메서드의 간단한 사용을 보여 줍니다 Read .

using namespace System;
using namespace System::IO;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         while ( sr->Peek() >= 0 )
         {
            Console::Write( (Char)sr->Read() );
         }
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
using System;
using System.IO;

class Test
{
    
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    Console.Write((char)sr.Read());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() >= 0
                Console.Write(Convert.ToChar(sr.Read()))
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

다음 코드 예제에서는 메서드 오버로드를 사용하여 Read() 단일 문자를 읽고 ASCII 정수 출력의 서식을 10진수 및 16진수로 지정하는 방법을 보여 줍니다.

using namespace System;
using namespace System::IO;
int main()
{
   
   //Create a FileInfo instance representing an existing text file.
   FileInfo^ MyFile = gcnew FileInfo( "c:\\csc.txt" );
   
   //Instantiate a StreamReader to read from the text file.
   StreamReader^ sr = MyFile->OpenText();
   
   //Read a single character.
   int FirstChar = sr->Read();
   
   //Display the ASCII number of the character read in both decimal and hexadecimal format.
   Console::WriteLine( "The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar );
   
   //
   sr->Close();
}
using System;
using System.IO;

class StrmRdrRead
{
public static void Main()
    {
    //Create a FileInfo instance representing an existing text file.
    FileInfo MyFile=new FileInfo(@"c:\csc.txt");
    //Instantiate a StreamReader to read from the text file.
    StreamReader sr=MyFile.OpenText();
    //Read a single character.
    int FirstChar=sr.Read();
    //Display the ASCII number of the character read in both decimal and hexadecimal format.
    Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.",
        FirstChar, FirstChar);
    //
    sr.Close();
    }
}
Imports System.IO

Class StrmRdrRead
   
   Public Shared Sub Main()
      'Create a FileInfo instance representing an existing text file.
      Dim MyFile As New FileInfo("c:\csc.txt")
      'Instantiate a StreamReader to read from the text file.
      Dim sr As StreamReader = MyFile.OpenText()
      'Read a single character.
      Dim FirstChar As Integer = sr.Read()
      'Display the ASCII number of the character read in both decimal and hexadecimal format.
      Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar)
      sr.Close()
   End Sub
End Class

설명

이 메서드는 TextReader.Read를 재정의합니다.

이 메서드는 스트림의 끝에 도달한 경우 -1을 반환할 수 있도록 정수 를 반환합니다. 데이터를 버퍼로 읽은 후 기본 스트림의 위치를 조작하는 경우 기본 스트림의 위치가 내부 버퍼의 위치와 일치하지 않을 수 있습니다. 내부 버퍼를 다시 설정하려면 메서드를 DiscardBufferedData 호출합니다. 그러나 이 메서드는 성능을 저하시키며 절대적으로 필요한 경우에만 호출해야 합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Read(Span<Char>)

Source:
StreamReader.cs
Source:
StreamReader.cs
Source:
StreamReader.cs

현재의 스트림에서 범위로 문자를 읽어 들입니다.

public:
 override int Read(Span<char> buffer);
public override int Read (Span<char> buffer);
override this.Read : Span<char> -> int
Public Overrides Function Read (buffer As Span(Of Char)) As Integer

매개 변수

buffer
Span<Char>

이 메서드가 반환될 경우, 현재의 소스에서 읽은 문자로 대체된 문자의 지정된 범위를 포함합니다.

반환

읽은 문자 수를 반환하거나 스트림의 끝에 있고 읽은 데이터가 없으면 0을 반환합니다. 데이터가 스트림 내에서 가용한지에 따라 이 수는 buffer 길이보다 작거나 같을 수 있습니다.

예외

스트림에서 읽은 문자 수가 buffer 길이보다 큽니다.

buffer이(가) null인 경우

적용 대상

Read(Char[], Int32, Int32)

Source:
StreamReader.cs
Source:
StreamReader.cs
Source:
StreamReader.cs

현재 스트림에서 지정된 최대 문자를 지정된 인덱스부터 버퍼로 읽어 들입니다.

public:
 override int Read(cli::array <char> ^ buffer, int index, int count);
public override int Read (char[] buffer, int index, int count);
override this.Read : char[] * int * int -> int
Public Overrides Function Read (buffer As Char(), index As Integer, count As Integer) As Integer

매개 변수

buffer
Char[]

이 메서드는 지정된 문자 배열의 값이 index 및 (index + count - 1) 사이에서 현재 원본으로부터 읽어온 문자로 교체된 상태로 반환됩니다.

index
Int32

쓰기를 시작할 buffer의 인덱스입니다.

count
Int32

읽을 최대 문자 수입니다.

반환

읽은 문자 수를 반환하거나 스트림의 끝에 있고 읽은 데이터가 없으면 0을 반환합니다. 이 수는 스트림 내에서 데이터를 사용할 수 있는지 여부에 따라 count 매개 변수보다 작거나 같습니다.

예외

버퍼 길이에서 index를 빼면 count보다 작습니다.

buffer이(가) null인 경우

index 또는 count가 음수입니다.

I/O 오류(예: 스트림이 닫혀 있음)가 발생합니다.

예제

다음 코드 예제에서는 파일의 끝에 도달할 때까지 한 번에 5자를 읽습니다.

using namespace System;
using namespace System::IO;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         //This is an arbitrary size for this example.
         array<Char>^c = nullptr;
         while ( sr->Peek() >= 0 )
         {
            c = gcnew array<Char>(5);
            sr->Read( c, 0, c->Length );
            
            //The output will look odd, because
            //only five characters are read at a time.
            Console::WriteLine( c );
         }
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
using System;
using System.IO;

class Test
{
    
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path))
            {
                //This is an arbitrary size for this example.
                char[] c = null;

                while (sr.Peek() >= 0)
                {
                    c = new char[5];
                    sr.Read(c, 0, c.Length);
                    //The output will look odd, because
                    //only five characters are read at a time.
                    Console.WriteLine(c);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() >= 0
                'This is an arbitrary size for this example.
                Dim c(5) As Char
                sr.Read(c, 0, c.Length)
                'The output will look odd, because
                'only five characters are read at a time.
                Console.WriteLine(c)
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

설명

이 메서드는 TextReader.Read를 재정의합니다.

이 메서드는 스트림의 끝에 도달한 경우 0을 반환할 수 있도록 정수 를 반환합니다.

메서드를 Read 사용하는 경우 스트림의 내부 버퍼와 크기가 같은 버퍼를 사용하는 것이 더 효율적입니다. 여기서 내부 버퍼는 원하는 블록 크기로 설정되며 항상 블록 크기보다 적게 읽습니다. 스트림이 생성될 때 내부 버퍼의 크기를 지정하지 않은 경우 기본 크기는 4K바이트(4096바이트)입니다. 데이터를 버퍼로 읽은 후 기본 스트림의 위치를 조작하는 경우 기본 스트림의 위치가 내부 버퍼의 위치와 일치하지 않을 수 있습니다. 내부 버퍼를 다시 설정하려면 메서드를 DiscardBufferedData 호출합니다. 그러나 이 메서드는 성능을 저하시키며 절대적으로 필요한 경우에만 호출해야 합니다.

이 메서드는 매개 변수에 지정된 count 문자 수를 읽거나 파일 끝에 도달한 후 를 반환합니다. ReadBlock 는 의 차단 버전입니다 Read.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상