Java Reference
In-Depth Information
Self-Test Exercises (continued)
5. Write some code that will create a stream named outStream that is a member of
the class PrintWriter , and that connects this stream to a text file named sam so
that your program can send output to the file. Do this in a way such that the file
sam always starts out empty. So, if there already is a file named sam , the old con-
tents of sam are lost.
6. As in Self-Test Exercise 5, write some code that will create a stream named
outStream that is a member of the class PrintWriter , and that connects this
stream to a text file named sam so that your program can send output to the file.
This time, however, do it in such a way that, if the file sam already exists, the old
contents of sam will not be lost and the program output will be written after the
old contents of the file.
7. The class Person was defined in Display 5.19 of Chapter 5. Suppose mary is an
object of the class Person , and suppose outputStream is connected to a text file as
in Display 10.1. Will the following send sensible output to the file connected to
outputStream ?
outputStream.println(mary);
Reading from a Text File
The two most common stream classes used for reading from a text file are the Scanner
class and the BufferedReader class. We will discuss both of these approaches to read-
ing from a text file. The Scanner class offers a richer group of methods for reading
from a text file and is our preferred class to use when reading from a text file. However,
the BufferedReader class is also widely used and is a reasonable choice. You, or your
instructor, will need to decide which class you will use.
Reading a Text File Using Scanner
The same Scanner class that we used for reading from the keyboard can also be used
for reading from a text file. To do so, you replace the argument System.in (in the
Scanner constructor) with a suitable stream that is connected to the text file. This is a
good illustration of the notion of a stream . The class Scanner does not care if its stream
argument comes from the keyboard or from a text file.
The use of Scanner for reading from a text file is illustrated in Display 10.3, which
contains a program that reads three numbers and a line of text from a text file named
morestuff.txt and writes them back to the screen. The file morestuff.txt is a text
file that a person could have created with a text editor or that a Java program could
have created using PrintWriter .
Search WWH ::




Custom Search