HOW TO:讀取和寫入新建立的資料檔案
BinaryWriter 和 BinaryReader 類別是用來寫入和讀取資料,而非字元字串。 下列程式碼範例示範對新的空白檔案資料流 (Test.data) 寫入和讀取資料。 在目前目錄中建立資料檔案之後,會建立相關的 BinaryWriter 和 BinaryReader,並使用 BinaryWriter 將 0 至 10 的整數寫入到 Test.data,使檔案指標停留在檔案結尾。 將檔案指標設定回起點後,BinaryReader 會讀出指定的內容。
範例
Imports System
Imports System.IO
Class MyStream
Private Const FILE_NAME As String = "Test.data"
Public Shared Sub Main()
' Create the new, empty data file.
If File.Exists(FILE_NAME) Then
Console.WriteLine("{0} already exists!", FILE_NAME)
Return
End If
Using fs As New FileStream(FILE_NAME, FileMode.CreateNew)
' Create the writer for data.
Using w As New BinaryWriter(fs)
' Write data to Test.data.
For i As Integer = 0 To 10
w.Write(i)
Next
End Using
End Using
' Create the reader for data.
Using fs As New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
Using r As New BinaryReader(fs)
' Read data from Test.data.
For i As Integer = 0 To 10
Console.WriteLine(r.ReadInt32())
Next
End Using
End Using
End Sub
End Class
using System;
using System.IO;
class MyStream
{
private const string FILE_NAME = "Test.data";
public static void Main()
{
// Create the new, empty data file.
if (File.Exists(FILE_NAME))
{
Console.WriteLine("{0} already exists!", FILE_NAME);
return;
}
using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew))
{
// Create the writer for data.
using (BinaryWriter w = new BinaryWriter(fs))
{
// Write data to Test.data.
for (int i = 0; i < 11; i++)
{
w.Write(i);
}
}
}
// Create the reader for data.
using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read))
{
using (BinaryReader r = new BinaryReader(fs))
{
// Read data from Test.data.
for (int i = 0; i < 11; i++)
{
Console.WriteLine(r.ReadInt32());
}
}
}
}
}
using namespace System;
using namespace System::IO;
ref class MyStream
{
private:
static String^ FILE_NAME = "Test.data";
public:
static void Main()
{
// Create the new, empty data file.
if (File::Exists(FILE_NAME))
{
Console::WriteLine("{0} already exists!", FILE_NAME);
return;
}
FileStream^ fs = gcnew FileStream(FILE_NAME, FileMode::CreateNew);
// Create the writer for data.
BinaryWriter^ w = gcnew BinaryWriter(fs);
// Write data to Test.data.
for (int i = 0; i < 11; i++)
{
w->Write(i);
}
w->Close();
fs->Close();
// Create the reader for data.
fs = gcnew FileStream(FILE_NAME, FileMode::Open, FileAccess::Read);
BinaryReader^ r = gcnew BinaryReader(fs);
// Read data from Test.data.
for (int i = 0; i < 11; i++)
{
Console::WriteLine(r->ReadInt32());
}
fs->Close();
}
};
int main()
{
MyStream::Main();
}
穩固程式設計
如果 Test.data 已存在於目前目錄中,則會擲回 IOException。 使用 FileMode.Create 一定會建立新檔案,且不會擲回 IOException。