Basic Classes for Input/Output in Java
In Java (as in most object-oriented languages), classes are designed with specific, well-defined
behavior. The input/output classes are a classic example of this philosophy.
The Source of the Data
- Traditionally data came from disk files or the keyboard.
- In some languages, these two data sources were treated identiacally, in others (usualy older languages),
keyboard and disk file input were handled differently.
- In Java, we'd like to keep our options open and flexible-- keyboard data, file data, data from a web page,
etc.
- There is a class called
FileInputStream
whose behavior is to read 8-bit 'characters' from
a disk file.
The ASCII/Unicode Dichotomy
- With the advent of the global reach of the internet, it became desireable to support alphabets other
than the standard Latin character set used in English.
- The introduction of Unicode and its 16-bit character induced Java to use a 16-bit character
type (rather than the traditional 8-bit ASCII).
- However, most data files were still encoded in 8-bit ASCII, and thus a translation was needed.
- In Java, ASCII (i.e.. 8-bit) input is handled by a family of classes known as
InputStreams
s;
while Unicode input is handled by the family of classes known as Readers
.
- There is a class called
InputStreamReader
whose behavior is to translate 8-bit 'characters'
into full 16-bit Unicode characters.
Buffering the Input
- The basic
InputStream
and Reader
classes read single characters at a time.
- The class
BufferedReader
buffers
(i.e., groups) characters together into
sequences of lines. This class provides the method readLine
which returns a String
containing the next line of the file.
Opening and Reading a File
Thus, to open a file for input, one would:
- Create a
FileInputStream
object, specfiying the file
- Create a
InputStreamReader
object, providing it with the
FileInputStream
object.
- Create a
BufferedReader
object, providing it with the InputStreamReader
object (which is a Reader
object).
- Invoke the
readLine
method on the BufferedReader
object.
Accessing the I/O Classes
In order to work conveniently with the I/O classes, you must place the statement
import java.io.*;
at the beginning of your source file (think of it as analogous to a #include
--
we'll go into more detail later).