Java Reference
In-Depth Information
Now that we have discussed the differences between input and output streams versus
readers and writers and also the difference between low-level and high-level streams, let's
see how to put this information to good use by demonstrating how to read and write from
fi les.
File Input and Output
The exam objectives state that “given a scenario involving navigating fi le systems, reading
from fi les, writing to fi les, or interacting with the user, develop the correct solution using
the following classes (sometimes in combination), from
java.io
:
BufferedReader
,
BufferedWriter
,
File
,
FileReader
,
FileWriter
,
PrintWriter
, and
Console
.” This section
discusses the details of these classes and how to use them to read and write data from fi les.
We start with the
FileReader
and
FileWriter
classes.
The
FileReader
and
FileWriter
Classes
The
FileReader
and
FileWriter
classes are used for reading and writing character data
from fi les. Let's look at an example. Suppose you want to read the data from the following
text fi le named
states.txt
:
New York
Alabama
South Dakota
Nevada
Because the data is in a fi le, we need to use either
FileInputStream
or
FileReader
to read
the data. Because the fi le only contains characters,
FileReader
is the better choice here. The
states are separated by the linefeed character, so we need to read the text in line by line, not
a built-in capability of the
FileReader
class. However, if we chain a
BufferedReader
object
to the
FileReader
, we can use the
readLine
method of
BufferedReader
to easily read in each
state in the fi le, as the following program shows:
1. import java.io.*;
2.
3. public class States {
4. public static void main(String [] args) {
5. try {
6. FileReader fileReader = new FileReader(“states.txt”);
7. BufferedReader in = new BufferedReader(fileReader);
8. String currentState = in.readLine();
Search WWH ::
Custom Search