Java Reference
In-Depth Information
Self-Test Exercises (continued)
4. Does the class PrintWriter have a constructor that accepts a string (for a fi le
name) as an argument, so that the following code would be legal?
PrintWriter outputStream =
new PrintWriter("stuff.txt");
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 fi le named sam so that
your program can send output to the fi le. Do this so that the fi le sam always starts
out empty. So, if there already is a fi le named sam , the old contents 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 fi le named sam so that your program can send output to the fi le.
This time, however, do it in such a way that, if the fi le 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 fi le.
7. The class Person was defi ned in Display 5.19 of Chapter 5 . Suppose mary is an
object of the class Person , which has a toString method defi ned, and suppose
outputStream is connected to a text fi le as in Display 10.1. Will the following
send sensible output to the fi le 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
reading 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.
VideoNote
Reading a Text
File
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, 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