TextReader
. In general, these methods can throw
an
IOException
on error. (Some can throw other types of exceptions, too.) Of particular
interest is the
ReadLine( )
method, which reads an entire line of text, returning it as a
string
.
This method is useful when reading input that contains embedded spaces.
TextWriter
defines versions of
Write( )
and
WriteLine( )
that output all of the built-in
types. For example, here are just a few of their overloaded versions:
Method
Description
void Write(int
val
)
Writes an
int
.
void Write(double
val
)
Writes a
double
.
void Write(bool
val
)
Writes a
bool
.
void WriteLine(string
val
)
Writes a
string
followed by a newline.
void WriteLine(uint
val)
Writes a
uint
followed by a newline.
void WriteLine(char
val
)
Writes a character followed by a newline.
All throw an
IOException
if an error occurs while writing.
TextWriter
also defines the
Close( )
and
Flush( )
methods shown here:
virtual void Close( )
virtual void Flush( )
Flush( )
causes any data remaining in the output buffer to be written to the physical
medium.
Close( )
closes the stream.
Method
Description
int Peek( )
Obtains the next character from the input stream,
but does not remove that character. Returns –1 if no
character is available.
int Read( )
Returns an integer representation of the next
available character from the invoking input stream.
Returns –1 when the end of the stream
is encountered.
int Read(char[ ]
buf
, int
offset
,
int
numChars
)
Attempts to read up to
numChars
characters into
buf
star ting at
buf
[
offset
], returning the number of
characters successfully read.
int ReadBlock(char[ ]
buf
, int
offset
,
int
numChars
)
Attempts to read up to
numChars
characters into
buf
star ting at
buf
[
offset
], returning the number of
characters successfully read.
string ReadLine( )
Reads the next line of text and returns it as a string.
Null is returned if an attempt is made to read at end-
of-file.
string ReadToEnd( )
Reads all of the remaining characters in a stream
and returns them as a string.
T
ABLE
14-3
The Input Methods Defi ned by
TextReader
www.freepdf-books.com
PART I
C h a p t e r 1 4 :
U s i n g I / O
367
PART IPART I
The
TextReader
and
TextWriter
classes are implemented by several character-based
stream classes, including those shown here. Thus, these streams provide the methods and
properties specified by
TextReader
and
TextWriter
.
Stream Class
Description
StreamReader
Read characters from a byte stream. This class wraps a byte input stream.
StreamWriter
Write characters to a byte stream. This class wraps a byte output stream.
StringReader
Read characters from a string.
StringWriter
Write characters to a string.
Binary Streams
In addition to the byte and character streams, there are two binary stream classes that can
be used to read and write binary data directly. These streams are called
BinaryReader
and
BinaryWriter
. We will look closely at these later in this chapter when binary file I/O is
discussed.
Now that you understand the general layout of the I/O system, the rest of this chapter
will examine its various pieces in detail, beginning with console I/O.
Console I/O
Console I/O is accomplished through the standard streams
Console.In
,
Console.Out
, and
Console.Error
. Console I/O has been used since Chapter 2, so you are already familiar with
it. As you will see, it has some additional capabilities.
Before we begin, however, it is important to emphasize a point made earlier in this book:
Most real applications of C# will not be text-based, console programs. Rather, they will be
graphically oriented programs or components that rely upon a windowed interface for
interaction with the user, or will be server-side code. Thus, the portion of the I/O system
that relates to console input and output is not widely used. Although text-based programs
are excellent as teaching examples, for short utility programs, and for some types of
components, they are not suitable for most real-world applications.
Reading Console Input
Console.In
is an instance of
TextReader
, and you can use the methods and properties
defined by
TextReader
to access it. However, you will generally use the methods provided
by
Console
, which automatically read from
Console.In
.
Console
defines three input methods.
The first two,
Read( )
and
ReadLine( )
, have been available since .NET Framework 1.0. The
third,
ReadKey( )
, was added by .NET Framework 2.0.
To read a single character, use the
Read( )
method:
static int Read( )
Read( )
returns the next character read from the console. It waits until the user presses a key
and then returns the result. The character is returned as an
int
, which must be cast to
char
.
Read( )
returns –1 on error. This method will throw an
IOException
on failure. When using
Read( )
, console input is line-buffered, so you must press
ENTER
before any character that
you type will be sent to your program.
www.freepdf-books.com
368
P a r t I :
T h e C # L a n g u a g e
Here is a program that reads a character from the keyboard using
Read( )
:
// Read a character from the keyboard.
using System;
class KbIn {
static void Main() {
char ch;
Console.Write("Press a key followed by ENTER: ");
ch = (char) Console.Read(); // get a char
Console.WriteLine("Your key is: " + ch);
}
}
Here is a sample run:
Press a key followed by ENTER: t
Your key is: t
The fact that
Read( )
is line-buffered is a source of annoyance at times. When you press
ENTER
, a carriage-return, line-feed sequence is entered into the input stream. Furthermore,
these characters are left pending in the input buffer until you read them. Thus, for some
applications, you may need to remove them (by reading them) before the next input operation.
(To read keystrokes from the console in a non-line-buffered manner, you can use
ReadKey( )
,
described later in this section.)
To read a string of characters, use the
ReadLine( )
method. It is shown here:
static string ReadLine( )
ReadLine( )
reads characters until you press
ENTER
and returns them in a
string
object. This
method will also throw an
IOException
on failure.
Here is a program that demonstrates reading a string from
Console.In
by using
ReadLine( )
:
// Input from the console using ReadLine().
using System;
class ReadString {
static void Main() {
string str;
Console.WriteLine("Enter some characters.");
str = Console.ReadLine();
Console.WriteLine("You entered: " + str);
}
}
Here is a sample run:
www.freepdf-books.com
Do'stlaringiz bilan baham: |