Java Reference
In-Depth Information
Text Files versus Binary Files
Files that you write and read using an editor are called
text files
.
Binary files
represent data
in a way that is not convenient to read with a text editor, but that can be written to and read
from a program very efficiently.
Self-Test Exercises
1. A stream is a flow of data. From where and to where does the data flow in an
input stream? From where and to where does the data flow in an output stream?
2. What is the difference between a binary file and a text file?
10.2
Text Files
Polonius: What do you read, my lord?
Hamlet: Words, words, words.
WILLIAM SHAKESPEARE,
Hamlet
In this section, we describe the most common ways to do text file I/O in Java.
Writing to a Text File
The class
PrintWriter
is the preferred stream class for writing to a text file. An object
of the class
PrintWriter
has the methods
print
and
println
, which are like the
methods
System.out.print
and
System.out.println
that you can use for screen
output. However, with an object of the class
PrintWriter
, the output goes to a text
file. Display 10.1 contains a simple program that uses
PrintWriter
to send output to
a text file. Let's look at the details of that program.
All the file I/O-related classes we introduce in this chapter are in the package
java.io
,
so all our program files begin with import statements similar to the ones in Display 10.1.
The program in Display 10.1 creates a text file named
stuff.txt
that a person can
read using an editor, or that another Java program can read. The program creates an
object of the class
PrintWriter
as follows:
PrintWriter
java.io
outputStream =
new
PrintWriter(
new
FileOutputStream("stuff.txt"));
The variable
outputStream
is of type
PrintWriter
and is declared outside the
try
block. The preceding two lines of code connect the stream named
outputStream
to
the file named
stuff.txt
. This is called
opening the file
. When you connect a file to a
stream in this way, your program always starts with an empty file. If the file
stuff.txt
opening a file