StreamReader.Read 方法

定义

读取输入流中的下一个字符或下一组字符。

重载

Read()

读取输入流中的下一个字符并使该字符位置提升一个字符。

Read(Span<Char>)

将当前流中的字符读入范围。

Read(Char[], Int32, Int32)

从指定的索引位置开始将来自当前流的指定的最多字符读到缓冲区。

Read()

读取输入流中的下一个字符并使该字符位置提升一个字符。

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

返回

Int32

输入流中表示为 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

下面的代码示例演示如何使用 方法重载读取单个字符,将 ASCII 整数输出格式化 Read() 为十进制和十六进制。

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

将当前流中的字符读入范围。

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>

此方法返回时,包含指定的字符范围,这些字符由从当前源中读取的字符替换。

返回

Int32

已读取的字符数,或者如果已到达流结尾并且未读取任何数据,则为 0。 该数小于或等于 buffer 长度,具体取决于流中是否有可用的数据。

例外

从流中读取的字符数大于 buffer 长度。

buffernull

适用于

Read(Char[], Int32, Int32)

从指定的索引位置开始将来自当前流的指定的最多字符读到缓冲区。

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

最多读取的字符数。

返回

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 千字节 (4096 字节) 。 如果在将数据读入缓冲区后操作基础流的位置,则基础流的位置可能与内部缓冲区的位置不匹配。 若要重置内部缓冲区,请调用 方法;但是,此方法会降低性能,应仅在绝对必要 DiscardBufferedData 时调用。

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

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

另请参阅

适用于