ArgumentNullException
is thrown. If
outputStream
has not been opened for writing,
ArgumentException
is thrown.
BinaryWriter
defines methods that can write all of C#’s built-in types. Several are
shown in Table 14-5. Notice that a
string
is written using its internal format, which includes
a length specifier.
BinaryWriter
also defines the standard
Close( )
and
Flush( )
methods,
which work as described earlier.
BinaryReader
A
BinaryReader
is a wrapper around a byte stream that handles the reading of binary data.
Its most commonly used constructor is shown here:
BinaryReader(Stream
inputStream
)
Here,
inputStream
is the stream from which data is read. To read from a file, you can use
the object created by
FileStream
for this parameter. If
inputStream
has not been opened for
reading or is otherwise invalid,
ArgumentException
is thrown.
BinaryReader
provides methods for reading all of C#’s simple types. Several commonly
used methods are shown in Table 14-6. Notice that
ReadString( )
reads a
string
that is stored
using its internal format, which includes a length specifier. These methods throw an
IOException
if an error occurs. (Other exceptions are also possible.)
Method
Description
void Write(sbyte
val
)
Writes a signed byte.
void Write(byte
val
)
Writes an unsigned byte.
void Write(byte[ ]
buf
)
Writes an array of bytes.
void Write(shor t
val
)
Writes a shor t integer.
void Write(ushor t
val
)
Writes an unsigned shor t integer.
void Write(int
val
)
Writes an integer.
void Write(uint
val
)
Writes an unsigned integer.
void Write(long
val
)
Writes a long integer.
void Write(ulong
val
)
Writes an unsigned long integer.
void Write(float
val
)
Writes a
float
.
void Write(double
val
)
Writes a
double
.
void Write(char
val
)
Writes a character.
void Write(char[ ]
buf
)
Writes an array of characters.
void Write(string
val
)
Writes a
string
using its internal representation, which includes a
length specifier.
T
ABLE
14-5
Commonly Used Output Methods Defi ned by
BinaryWriter
www.freepdf-books.com
PART I
C h a p t e r 1 4 :
U s i n g I / O
385
PART IPART I
BinaryReader
also defines three versions of
Read( )
, which are shown here:
Method
Description
int Read( )
Returns an integer representation of the next
available character from the invoking input stream.
Returns –1 when attempting to read at the end of
the file.
int Read(byte[ ]
buf
, int
offset
, int
num
)
Attempts to read up to
num
bytes into
buf
star ting
at
buf
[
offset
], returning the number of bytes
successfully read.
int Read(char[ ]
buf
, int
offset
, int
num
)
Attempts to read up to
num
characters into
buf
star ting at
buf
[
offset
], returning the number of
characters successfully read.
These methods will throw an
IOException
on failure. Other exceptions are possible. Also
defined is the standard
Close( )
method.
Method
Description
bool ReadBoolean( )
Reads a
bool
.
byte ReadByte( )
Reads a
byte
.
sbyte ReadSByte( )
Reads an
sbyte
.
byte[ ] ReadBytes(int
num
)
Reads
num
bytes and returns them as an array.
char ReadChar( )
Reads a
char
.
char[ ] ReadChars(int
num
)
Reads
num
characters and returns them as an array.
double ReadDouble( )
Reads a
double
.
float ReadSingle( )
Reads a
float
.
shor t ReadInt16( )
Reads a
short
.
int ReadInt32( )
Reads an
int
.
long ReadInt64( )
Reads a
long
.
ushor t ReadUInt16( )
Reads a
ushort
.
uint ReadUInt32( )
Reads a
uint
.
ulong ReadUInt64( )
Reads a
ulong
.
string ReadString( )
Reads a
string
that is represented in its internal, binar y
format, which includes a length specifier. This method
should only be used to read a string that has been written
using a
BinaryWriter
.
T
ABLE
14-6
Commonly Used Input Methods Defi ned by
BinaryReader
www.freepdf-books.com
386
P a r t I :
T h e C # L a n g u a g e
Demonstrating Binary I/O
Here is a program that demonstrates
BinaryReader
and
BinaryWriter
. It writes and then
reads back various types of data to and from a file.
// Write and then read back binary data.
using System;
using System.IO;
class RWData {
static void Main() {
BinaryWriter dataOut;
BinaryReader dataIn;
int i = 10;
double d = 1023.56;
bool b = true;
string str = "This is a test";
try {
dataOut = new
BinaryWriter(new FileStream("testdata", FileMode.Create));
}
catch(IOException exc) {
Console.WriteLine("Cannot Open File For Output");
Console.WriteLine(exc.Message);
return;
}
// Write data to a file.
try {
Console.WriteLine("Writing " + i);
dataOut.Write(i);
Console.WriteLine("Writing " + d);
dataOut.Write(d);
Console.WriteLine("Writing " + b);
dataOut.Write(b);
Console.WriteLine("Writing " + 12.2 * 7.4);
dataOut.Write(12.2 * 7.4);
Console.WriteLine("Writing " + str);
dataOut.Write(str);
}
catch(IOException exc) {
Console.WriteLine("Error Writing File");
Console.WriteLine(exc.Message);
}
dataOut.Close();
Console.WriteLine();
www.freepdf-books.com
PART I
C h a p t e r 1 4 :
U s i n g I / O
387
PART IPART I
// Now, read the data.
try {
dataIn = new
BinaryReader(new FileStream("testdata", FileMode.Open));
}
catch(IOException exc) {
Console.WriteLine("Cannot Open File For Input");
Console.WriteLine(exc.Message);
return;
}
try {
i = dataIn.ReadInt32();
Console.WriteLine("Reading " + i);
d = dataIn.ReadDouble();
Console.WriteLine("Reading " + d);
b = dataIn.ReadBoolean();
Console.WriteLine("Reading " + b);
d = dataIn.ReadDouble();
Console.WriteLine("Reading " + d);
str = dataIn.ReadString();
Console.WriteLine("Reading " + str);
}
catch(IOException exc) {
Console.WriteLine("Error Reading File");
Console.WriteLine(exc.Message);
}
dataIn.Close();
}
}
The output from the program is shown here:
Writing 10
Writing 1023.56
Writing True
Writing 90.28
Writing This is a test
Reading 10
Reading 1023.56
Reading True
Reading 90.28
Reading This is a test
If you examine the
testdata
file produced by this program, you will find that it contains
binary data, not human-readable text.
Here is a more practical example that shows how powerful binary I/O is. The following
program implements a very simple inventory program. For each item in the inventory, the
www.freepdf-books.com
388
P a r t I :
T h e C # L a n g u a g e
program stores the item’s name, the number on hand, and its cost. Next, the program prompts
the user for the name of an item. It then searches the database. If the item is found, the
inventory information is displayed.
/* Use BinaryReader and BinaryWriter to implement
a simple inventory program. */
using System;
using System.IO;
class Inventory {
static void Main() {
BinaryWriter dataOut;
BinaryReader dataIn;
string item; // name of item
int onhand; // number on hand
double cost; // cost
try {
dataOut = new
BinaryWriter(new FileStream("inventory.dat",
FileMode.Create));
}
catch(IOException exc) {
Console.WriteLine("Cannot Open Inventory File For Output");
Console.WriteLine(exc.Message);
return;
}
// Write some inventory data to the file.
try {
dataOut.Write("Hammers");
dataOut.Write(10);
dataOut.Write(3.95);
dataOut.Write("Screwdrivers");
dataOut.Write(18);
dataOut.Write(1.50);
dataOut.Write("Pliers");
dataOut.Write(5);
dataOut.Write(4.95);
dataOut.Write("Saws");
dataOut.Write(8);
dataOut.Write(8.95);
}
catch(IOException exc) {
Console.WriteLine("Error Writing Inventory File");
Console.WriteLine(exc.Message);
}
dataOut.Close();
www.freepdf-books.com
Do'stlaringiz bilan baham: |