Java Reference
In-Depth Information
hex) and for character 9 is 57 ( 0x39 in hex). Thus, to write the characters 199 , three bytes—
0x31 , 0x39 , and 0x39 —are sent to the output, as shown in Figure 19.2a.
Binary I/O does not require conversions. If you write a numeric value to a file using binary
I/O, the exact value in the memory is copied into the file. For example, a byte-type value 199
is represented as 0xC7 in the memory and appears exactly as 0xC7 in
the file, as shown in Figure 19.2b. When you read a byte using binary I/O, one byte value is
read from the input.
In general, you should use text input to read a file created by a text editor or a text output
program, and use binary input to read a file created by a Java binary output program.
Binary I/O is more efficient than text I/O, because binary I/O does not require encoding
and decoding. Binary files are independent of the encoding scheme on the host machine and
thus are portable. Java programs on any machine can read a binary file created by a Java pro-
gram. This is why Java class files are binary files. Java class files can run on a JVM on any
machine.
16 1
(199
=
12
*
+
7)
Note
For consistency, this topic uses the extension .txt to name text files and .dat to name
binary files.
.txt and .dat
19.3 What are the differences between text I/O and binary I/O?
19.4 How is a Java character represented in the memory, and how is a character repre-
sented in a text file?
19.5 If you write the string "ABC" to an ASCII text file, what values are stored in the file?
19.6 If you write the string "100" to an ASCII text file, what values are stored in the file?
If you write a numeric byte-type value 100 using binary I/O, what values are stored
in the file?
19.7 What is the encoding scheme for representing a character in a Java program? By
default, what is the encoding scheme for a text file on Windows?
Check
Point
19.4 Binary I/O Classes
The abstract InputStream is the root class for reading binary data and the abstract
OutputStream is the root class for writing binary data.
Key
Point
The design of the Java I/O classes is a good example of applying inheritance, where common
operations are generalized in superclasses, and subclasses provide specialized operations.
Figure 19.3 lists some of the classes for performing binary I/O. InputStream is the root for
FileInputStream
DataInputStream
InputStream
FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream
DataOutputStream
OutputStream
FilterOutputStream
BufferedOutputStream
ObjectOutputStream
F IGURE 19.3 InputStream , OutputStream , and their subclasses are for performing
binary I/O.
 
 
Search WWH ::




Custom Search