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 整数输出的格式设置为十进制和十六进制。

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 长度。

buffernull

适用于

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

buffernull

indexcount 为负数。

发生 I/O 错误,例如流关闭。

示例

下面的代码示例一次读取五个字符,直到到达文件末尾。

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 方法时,使用与流内部缓冲区大小相同的缓冲区更高效,其中内部缓冲区设置为所需的块大小,并且始终读取小于块大小。 如果在构造流时未指定内部缓冲区的大小,则其默认大小为 4 kb (4096 字节) 。 如果在将数据读取到缓冲区后操作基础流的位置,则基础流的位置可能与内部缓冲区的位置不匹配。 若要重置内部缓冲区,请调用 DiscardBufferedData 方法;但是,此方法会降低性能,仅应在绝对必要时调用。

在读取参数指定的 count 字符数或到达文件末尾后,此方法将返回 。 ReadBlock 是 的 Read阻止版本。

有关常见 I/O 任务的列表,请参阅 常见 I/O 任务

另请参阅

适用于