StreamReader.Peek 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
傳回下一個可供使用的字元,但不使用它。
public:
override int Peek();
public override int Peek ();
override this.Peek : unit -> int
Public Overrides Function Peek () As Integer
傳回
整數,表示要讀取的下一個字元,如果沒有要讀取的字元或資料流不支援搜尋,則為 -1。
例外狀況
發生 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
{
while ( sr->Peek() > -1 )
{
Console::WriteLine( sr->ReadLine() );
}
}
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() > -1)
{
Console.WriteLine(sr.ReadLine());
}
}
}
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() > -1
Console.WriteLine(sr.ReadLine())
Loop
sr.Close()
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
備註
方法會 Peek 傳回整數值,以判斷檔案的結尾還是發生另一個錯誤。 這可讓使用者先檢查傳回的值是否為 -1,再將其 Char 轉換成類型。
這個方法會覆寫 TextReader.Peek。
物件的目前位置 StreamReader 不會由 Peek變更。