如何:对新建的数据文件进行读取和写入
更新:2007 年 11 月
BinaryWriter 和 BinaryReader 类用于读取和写入数据,而不是用于读取和写入字符串。下面的代码示例演示如何向新的空文件流 (Test.data) 写入数据及从中读取数据。在当前目录中创建了数据文件之后,也就同时创建了相关的 BinaryWriter 和 BinaryReader,BinaryWriter 用于向 Test.data 写入整数 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。