Streams (Overview)
A stream is a flow of characters to and from a program. The other end of the stream can be anything that can accept or generate a stream of characters, including a console window, a printer, a file on a disk drive, or even another program.
The two basic types of streams in Java are
Character streams: Character streams read and write text characters that represent strings. You can connect a character stream to a text file to store text data on a hard drive. Typically, text files use special characters called delimiters — such as commas or Tabs — to separate elements of the file.
Binary streams: Binary streams read and write individual bytes that represent primitive data types. You can connect a binary stream to a binary file to store binary data on a hard drive. The contents of binary files make perfect sense to the programs that read and write them, but if you try to open a binary file in a text editor, the file’s contents look like gibberish.
Many of the classes described in this part are designed to facilitate stream I/O. For character streams, these classes are
Reader
: An abstract class that the other reader classes extend.
FileReader
: Provides basic methods for reading data from a character stream that originates from a file. This class reads data one character at a time. You don’t usually work with this class directly. Instead, you use it to connect to a BufferedReader
object, which can read the data more efficiently.
BufferedReader
: Provides more efficient input from a file-based character stream.
Scanner
: Reads characters from a stream and parses it into meaningful data.
Writer
: An abstract class that the other writer classes extend.
FileWriter
: Connects to a File
object and provides basic writing capabilities.
BufferedWriter
: Provides more-efficient file-writing capabilities than the basic FileWriter
class.
PrintWriter
: Writes data to a text file one line at a time. This class typically connects to a FileWriter
or BufferedWriter
class.
For binary streams, the relevant classes are
InputStream
: An abstract class that the other input stream classes extend.
FileInputStream
: Connects a binary input stream to a file.
BufferedInputStream
: Adds buffering abilities to FileInputStream
for more-efficient input.
DataInputStream
: Reads primitive data types from a binary input stream.
OutputStream
: An abstract class that the other output stream classes extend.
FileOutputStream
: Connects a binary output stream to a file.
BufferedOutputStream
: Adds buffering to FileOutputStream
.
DataOutputStream
: Writes primitive data types to a binary output stream.