방법: 새로 만든 데이터 파일 읽기 및 쓰기
업데이트: 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이 throw됩니다. IOException을 throw하지 않고 항상 새 파일을 만들려면 FileMode.Create를 사용합니다.