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