Page 650 - Introduction to Programming with Java: A Problem Solving Approach
P. 650
616 Chapter 15 Files
Text files are line oriented. When writing to a text file, PrintWriter’s println method automati- cally inserts an end-of-line symbol at the end of the line. In Microsoft Windows, it inserts \r\n. (\r is the carriage return symbol, and \n is the new line symbol.) In UNIX , it inserts \n only. When reading from a text file, Scanner’s nextLine method reads an entire line of characters, and it accepts either \r\n or \n by itself as a line terminator, but it does not include the terminator in the retrieved string. Since \n by itself is simpler, we’ll use it in our illustrations. Now let’s see what a text file looks like. Suppose you have this data:
Bob 2222
Paul5555
Figure 15.8 shows how it’s stored in a text file.
Figure 15.8 Raw form of text format
ASCII characters are shown in blue above each byte. Each logical line is terminated by the \n character, but in a file everything is strung together in one continuous sequence. Here the sequence wraps around so that everything fits within the available page width.
Apago PDF Enhancer
Now let’s analyze the actual storage for characters in this text file. The ASCII code value for ‘B’ is decimal 66. (B’s value, along with all the other ASCII code values can be found in Figure 11.4.) To find the equivalent binary value, identify the powers of two that add up to 66. 26 and 21 are the powers of two that add up to 66 (26 64, 21 2, and 64 2 66). For each identified power of two, use its exponent as a place marker for a 1 in the equivalent binary value. For the 66 example, the powers of two, 26 and 21, have 6 and 1 exponents, so the 6 and 1 bit positions are 1 in the following binary representation of 66. Note that bit positions start at 0 from the right side.
B
o
b
2
2
2
2
\n
P
01000010
01101111
01100010
00100000
00110010
00110010
00110010
00110010
00001010
01010000
a
u
l
5
5
5
5
\n
01100001
01110101
01101100
00110101
00110101
00110101
00110101
00001010
bit position 6
01000010
bit position 1
Here’s the mathematical explanation of why decimal 66 is equivalent to binary 01000010: 66(642)(26 21)(0*27 1*26 0*25 0*24 0*23 0*22 1*21 0*20)
(01000010)
The ASCII code value for a space character is decimal 32. The binary value is:
32(25)(0*27 0*26 1*25 0*24 0*23 0*22 0*21 0*20)(00100000) The ASCII code value for ‘2’ is decimal 50. The binary value is:
50(32162)(25 24 21)
(0*27 0*26 1*25 1*24 0*23 0*22 1*21 0*20) (00110010)
The ASCII code value for the new line character is decimal 10. The binary value is:
10(82)(23 21)(0*27 0*26 0*25 0*24 1*23 0*22 1*21 0*20)(00001010)