Reading and Writing |
Processing streams perform some sort of operation, such as buffering or character encoding, as they read and write. Like the data sink streams,java.io
often contains pairs of streams: one that performs a particular operation during reading and another that performs the same operation (or reverses it) during writing. This table givesjava.io
's processing streams.[PENDING: get table from book]
Notice that many times,
java.io
contains character streams and byte streams that perform the same processing but for the different data type. The processing streams are briefly described here:
BufferedReader
andBufferedWriter
BufferedInputStream
andBufferedOutputStream
- Buffer data while reading or writing, thereby reducing the number of accesses required on the original data source. Buffered streams are typically more efficient than similar nonbuffered streams.
FilterReader
andFilterWriter
FilterInputStream
andFilterOutputStream
- Abstract classes, like their parents. They define the interface for filter streams, which filter data as it's being read or written. Working with Filter Streams later in this lesson shows you how to use filter streams and how to implement your own.
InputStreamReader
andOutputStreamWriter
- A reader and writer pair that forms the bridge between byte streams and character streams. An
InputStreamReader
reads bytes from anInputStream
and converts them to characters using either the default character-encoding or a character-encoding specified by name. Similarly, anOutputStreamWriter
converts characters to bytes using either the default character-encoding or a character-encoding specified by name and then writes those bytes to anOutputStream
. You can learn the name of the default character-encoding by callingSystem.getProperty("file.encoding")
. Find out more about character-encoding in the Writing Global Programs trail.SequenceInputStream
- Concatenates multiple input streams into one input stream. How to Concatenate Files has a short example of this class.
ObjectInputStream
andObjectOutputStream
- Used to serialize objects. See Object Serialization.
DataInputStream
andDataOutputStream
- Read or write primitive Java data types in a machine-independent format. How to Use
DataInputStream
andDataOutputStream
shows you an example of using these two streams.LineNumberReader
LineNumberInputStream
- Keeps track of line numbers while reading.
PushbackReader
PushbackInputStream
- Two input streams each with a 1-character (or byte) pushback buffer. Sometimes, when reading data from a stream, you will find it useful to peek at the next item in the stream in order to decide what to do next. However, if you do peek ahead, you'll need to put the item back so that it can be read again and processed normally.
PrintWriter
PrintStream
- Contain convenient printing methods. These are the easiest streams to write to, so you will often see other writable streams wrapped in one of these.
Reading and Writing |