The Character Stream Wrapper Classes
To create a character stream, wrap a byte stream inside one of the character stream wrappers. At the top of the character stream hierarchy are the abstract classes TextReader and TextWriter. TextReader handles input, and TextWriter handles output. The methods defined by these two abstract classes are available to all of their subclasses. Thus, they form a minimal set of I/O functions that all character streams will have.
|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[ ] buffer, int index, int count)||Attempts to read up to count characters into buffer starting at buffer[count], returning the number of characters successfully read.|
|int ReadBlock(char[ ] buffer, int index, int count)||Attempts to read up to count characters into buffer starting at buffer[index], 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.|
Above Table shows the input methods in 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. TextReader also specifies the Close( ) method, shown here:
|void Write(int value)||Writes an int.|
|void Write(double value)||Writes a double.|
|void Write(bool value)||Writes a bool.|
|void WriteLine(string value)||Writes a string followed by a newline.|
|void WriteLine(uint value)||Writes a uint followed by a newline.|
|void WriteLine(char value)||Writes a char followed by a newline.|
All throw an IOException if an error occurs while writing. TextWriter also specifies 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 writer and frees its resources.
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.
|StreamReader||Reads characters from a byte stream. This class wraps a byte input stream.|
|StreamWriter||Writes characters to a byte stream. This class wraps a byte output stream.|
|StringReader||Reads characters from a string.|
|StringWriter||Writes characters to a string.|