Java Reference
In-Depth Information
Program
Input stream
Input object
created from an
input class
01011 . ..1001
File
Output object
created from an
output class
11001...1011
File
Output stream
F IGURE 19.1
The program receives data through an input object and sends data through an
output object.
19.1
What is a text file, and what is a binary file? Can you view a text file or a binary file
using a text editor?
Check
Point
19.2
How do you read or write text data in Java? What is a stream?
19.3 Text I/O vs. Binary I/O
Binary I/O does not involve encoding or decoding and thus is more efficient than text I/O.
Key
Point
Computers do not differentiate between binary files and text files. All files are stored in binary
format, and thus all files are essentially binary files. Text I/O is built upon binary I/O to pro-
vide a level of abstraction for character encoding and decoding, as shown in Figure 19.2a.
Encoding and decoding are automatically performed for text I/O. The JVM converts Unicode
to a file-specific encoding when writing a character, and it converts a file-specific encoding to
Unicode when reading a character. For example, suppose you write the string "199" using
text I/O to a file. Each character is written to the file. Since the Unicode for character 1 is
0x0031 , the Unicode 0x0031 is converted to a code that depends on the encoding scheme for
the file. (Note that the prefix 0x denotes a hex number.) In the United States, the default
encoding for text files on Windows is ASCII. The ASCII code for character 1 is 49 ( 0x31 in
Text I/O program
The Unicode of
the character
Encoding/
Decoding
The encoding of the character
is stored in the file
e.g., " 199 "
00110001 00111001 00111001
0x31
0x39
0x39
(a)
Binary I/O program
The same byte in the file
A byte is read/written
e.g., 199
11000111
0xC7
(b)
F IGURE 19.2
Text I/O requires encoding and decoding, whereas binary I/O does not.
 
 
Search WWH ::




Custom Search