Lesson 6 | Creating streams |
Objective | Create stream objects |
Creating Reader Streams in Java
Before you can read data from or write data to a stream, you must create a stream object. This typically involves using one of the stream subclasses. Following are the most commonly used subclasses of the Reader
class:
Stream: A stream is a medium through which data is transferred. A stream acts sort of like a pipe in the real world,
except that it shuttles moving data instead of water or gas. Data is transferred through a stream one byte at a time, and can be directed in different ways.
FileReader |
read characters from a text file |
StringReader |
read characters from a string in memory |
CharArrayReader |
read characters from an array of characters |
FilterReader |
filter a stream of input data |
BufferedReader |
buffer a stream of input data to memory |
FilterReader and BufferedReader Classes
The FilterReader
and BufferedReader
classes are not actually data sources;
they are used in conjunction with other stream objects. Following is an example of creating a buffered string reader:
Buffered I/O: Buffered I/O is a special type of I/O where data is written to a temporary buffer instead of to an actual stream.
When the buffer is full, all of the data in the buffer is written to the stream. Buffered I/O is more efficient than non-buffered I/O since data is transferred to and from a physical device in large blocks.
BufferedReader in = new BufferedReader(new StringReader(str));
Passing one stream object into another's constructor is how Java gives you flexibility in creating stream objects.
If you do not want the string reader to be buffered, you could simply create it like this:
StringReader in = new StringReader(str);
Creating writer streams
Creating writer stream objects is very similar to creating readers. Following are the most commonly used subclasses of the Writer
class:
FileWriter |
write characters to a text file |
StringWriter |
write characters to a string buffer |
CharArrayWriter |
write characters to a character buffer |
FilterWriter |
filter a stream of output data |
BufferedWriter |
buffer a stream of output data to memory |
PrintWriter |
write data formatted for display |
Following is an example of creating a buffered print writer that can be used to write formatted data to a text file named Out.txt
:
PrintWriter out = new PrintWriter(
new BufferedWriter(new FileWriter("Out.txt")));
Creating Reader Stream - Exercise