Java Reference
In-Depth Information
Character streams are used for storing and retrieving text. You may also use character streams to read text
files not written by a Java program. All binary numeric data has to be converted to a textual representation
before being written to a character stream. This involves generating a character representation of the original
binary data value. Reading numeric data from a stream that contains text involves much more work than
reading binary data. When you read a value of type int from a binary stream, you know that it consists of
four bytes.When you read an integer from a character stream, you have to determine how many characters
make up the value. For each numerical value you read from a character stream, you have to be able to
recognize where the value begins and ends, and then convert the token - the sequence of characters that
represents the value - to its binary form. This is illustrated below:
When you write strings to a stream as character data, by default, the Unicode characters are
automatically converted to the local representation of the characters in the host machine, and these are
then written to the stream. When you read a string, the default mechanism is to convert the data from
the stream back to Unicode characters from the local machine representation. With character streams,
your program reads and writes Unicode characters, but the stream will contain characters in the
equivalent character encoding used by the local computer.
You don't have to accept the default conversion process for character streams. Java allows named
mappings between Unicode characters and sets of bytes to be defined, called charsets , and you can
select an available charset that should apply when data is transferred to, or from, a particular character
stream. We won't be going into this in detail, but you can find more information on defining and using
charsets in the SDK documentation for the Charset class.
The Classes for Input and Output
There are quite a number of stream classes, but as you will see, they form a reasonably logical structure.
Once you see how they are related, you shouldn't have much trouble using them. We will work through
the class hierarchy from the top down, so you will be able to see how the classes hang together, and
how you can combine them in different ways to suit different situations.
The package java.io contains the classes that provide the foundation for Java's support for stream I/O:
Search WWH ::




Custom Search