Java Reference
In-Depth Information
Memory-Based
char
Array
Reader
s and
Writer
s
Classes
CharArrayReader
and
CharArrayWriter
read and write, respectively, a stream of
characters to a
char
array. A
LineNumberReader
(a subclass of
BufferedReader
) is a buff-
ered character stream that keeps track of the number of lines read—newlines, returns and
carriage-return-line-feed combinations increment the line count. Keeping track of line
numbers can be useful if the program needs to inform the reader of an error on a specific
line.
Character-Based File, Pipe and String
Reader
s and
Writer
s
An
InputStream
can be converted to a
Reader
via class
InputStreamReader
. Similarly, an
OutputStream
can be converted to a
Writer
via class
OutputStreamWriter
. Class
File-
Reader
(a subclass of
InputStreamReader
) and class
FileWriter
(a subclass of
Output-
StreamWriter
) read characters from and write characters to a file, respectively. Class
PipedReader
and class
PipedWriter
implement piped-character streams for transferring
data between threads. Class
StringReader
and
StringWriter
read characters from and
write characters to
String
s, respectively. A
PrintWriter
writes characters to a stream.
In this chapter, you learned how to manipulate persistent data. We compared byte-based
and character-based streams, and introduced several classes from packages
java.io
and
java.nio.file
. You used classes
Files
and
Paths
and interfaces
Path
and
Directo-
ryStream
to retrieve information about files and directories. You used sequential-access
file processing to manipulate records that are stored in order by the record-key field. You
learned the differences between text-file processing and object serialization, and used seri-
alization to store and retrieve entire objects. The chapter concluded with a small example
of using a
JFileChooser
dialog to allow users to easily select files from a GUI. The next
chapter discusses Java's classes for manipulating collections of data—such as class
Array-
List
, which we introduced in Section 7.16.
Summary
Section 15.1 Introduction
• Computers use files for long-term retention of large amounts of persistent data (p. 645), even
after the programs that created the data terminate.
• Computers store files on secondary storage devices (p. 645) such as hard disks.
Section 15.2 Files and Streams
• Java views each file as a sequential stream of bytes (p. 645).
• Every operating system provides a mechanism to determine the end of a file, such as an end-of-
file marker (p. 645) or a count of the total bytes in the file.
• Byte-based streams (p. 646) represent data in binary format.
• Character-based streams (p. 646) represent data as sequences of characters.
• Files created using byte-based streams are binary files (p. 646). Files created using character-
based streams are text files (p. 646). Text files can be read by text editors, whereas binary files are
read by a program that converts the data to a human-readable format.