Java Reference
In-Depth Information
C
HAPTER
S
UMMARY
1.
I/O can be classified into
text I/O
and
binary I/O
. Text I/O interprets data in sequences
of characters. Binary I/O interprets data as raw binary values. How text is stored in a file
depends on the encoding scheme for the file. Java automatically performs encoding and
decoding for text I/O.
2.
The
InputStream
and
OutputStream
classes are the roots of all binary I/O
classes.
FileInputStream/FileOutputStream
associates a file for input/output.
BufferedInputStream
/
BufferedOutputStream
can be used to wrap any binary
I/O stream to improve performance.
DataInputStream
/
DataOutputStream
can be
used to read/write primitive values and strings.
3.
ObjectInputStream
/
ObjectOutputStream
can be used to read/write objects in
addition to primitive values and strings. To enable object
serialization
, the object's
defining class must implement the
java.io.Serializable
marker interface.
4.
The
RandomAccessFile
class enables you to read and write data to a file. You can
open a file with the
r
mode to indicate that it is read-only or with the
rw
mode to indi-
cate that it is updateable. Since the
RandomAccessFile
class implements
DataInput
and
DataOutput
interfaces, many methods in
RandomAccessFile
are the same as
those in
DataInputStream
and
DataOutputStream
.
Q
UIZ
P
ROGRAMMING
E
XERCISES
Section 17.3
*17.1
(
Create a text file
) Write a program to create a file named
Exercise17_01.txt
if
it does not exist. Append new data to it if it already exists. Write 100 integers
created randomly into the file using text I/O. Integers are separated by a space.
Section 17.4
*17.2
(
Create a binary data file
) Write a program to create a file named
Exercise17_02.dat
if it does not exist. Append new data to it if it already exists.
Write 100 integers created randomly into the file using binary I/O.
*17.3
(
Sum all the integers in a binary data file
) Suppose a binary data file named
Exercise17_03.dat
has been created and its data are created using
writeInt(int)
in
DataOutputStream
. The file contains an unspecified
number of integers. Write a program to find the sum of the integers.
*17.4
(
Convert a text file into UTF
) Write a program that reads lines of characters from
a text file and writes each line as a UTF-8 string into a binary file. Display the
sizes of the text file and the binary file. Use the following command to run the
program:
java Exercise17_04 Welcome.java Welcome.utf
Search WWH ::
Custom Search