Game Development Reference
In-Depth Information
•
A
Stream
allows you to both read and write from the same file, as well as overwrite
parts of the file. A reader or writer only allows you to read or write, respectively.
22.5.3 Reader
A
reader
class allows reading bigger units than bytes. For example, a
TextReader
can read text (so: strings consisting of characters). It contains among others the
following methods:
−
int
Read();
// reads a char or returns
1 if the end of the file was reached
string
ReadLine();
// reads the next line
string
ReadToEnd();
// reads the rest of the file
A
BinaryReader
can read the basic types in their binary coding. An
int
or a
float
always takes 4 bytes, a
long
or a
double
always 8 bytes. This class has (among
others) the following methods:
byte
ReadByte();
short
ReadInt16();
int
ReadInt32();
long
ReadInt64();
uint
ReadUInt32();
double
ReadDouble();
Readers are
not
streams! Although some of them have a method
Read
or
ReadByte
,
these are other methods than the methods carrying the same name in
Stream
, with
other results. Some of the readers (such as
BinaryReader
) allow you to provide a
Stream
as a parameter in the constructor. For every reading operation the binary
reader will use the underlying stream to read the actual bytes. However, not all
readers use an underlying stream, some of them have an underlying string from
which they get the data.
22.5.4 Text Reader
It is not allowed to make instances directly of the class
TextReader
because it is an
abstract class
(more about that later on). If you want to use a kind of text reader,
you should use one of its subclasses. You can choose between two subclasses:
a
StreamReader
is a text reader that uses an underlying stream, a
StringReader
is a
text reader that uses an underlying string. In practice, you will probably use the
StreamReader
most of the times. This is also the class that we use in the example.
The naming of the different classes is slightly confusing:
•
a
BinaryReader
reads binary things from an underlying stream