Page 652 - Introduction to Programming with Java: A Problem Solving Approach
P. 652

                618 Chapter 15 Files
happens to be the largest positive number an int can hold. Since it’s a positive number, the most significant bit must be 0. Since it’s the largest positive number, all the other bits are 1. Sure enough, if you punch it out on your hand calculator, you’ll find that:
(01111111 11111111 11111111 11111111) 􏰀
(0*231 􏰁 1*230 􏰁 1*229 􏰁 1*228 􏰁 1*227 􏰁 1*226 􏰁 1*225 􏰁 1*224 􏰁
1*223 􏰁 1*222 􏰁 1*221 􏰁 1*220 􏰁 1*219 􏰁 1*218 􏰁 1*217 􏰁 1*216 􏰁 1*215 􏰁 1*214 􏰁 1*213 􏰁 1*212 􏰁 1*211 􏰁 1*210 􏰁 1*29 􏰁 1*28 􏰁 1*27 􏰁1*26 􏰁1*25 􏰁1*24 􏰁1*23 􏰁1*22 􏰁1*21 􏰁1*20)􏰀
2147483647
Trade-Offs
Benefits of text files:
• Independentcreation—usingUNIXvi,MicrosoftNotepad,Wordpad,WordTextFile,andsoon. • Independentviewing—usingalmostanywordprocessororothercomputerlanguage.
Benefits of binary files or object files:
• Can handle all Unicode characters • Moreefficientnumberstorage
• Canstorecomplexobjects
            Apago PDF Enhancer
15.7 Binary File I/O
In Java it’s straightforward to store primitive data in binary files. From a hardware perspective, it’s the most
efficient storage strategy.
Output
To open a binary file for primitive data output, instantiate a FileOutputStream object. This sends a stream of bytes to the file. To transform primitive data types into bytes, instantiate a DataOutputStream object. The FileOutputStream class descends from the OutputStream class, and the only DataOutputStream constructor has an OutputStream type of parameter, so you can pass the new FileOutputStream object directly into the DataOutputStream constructor as an argument like this:7
DataOutputStream fileOut;
...
fileOut =
 new DataOutputStream(new FileOutputStream(stdIn.nextLine(), true));
...
 7 Optionally, you can speed up execution by inserting a BufferedOutputStream object between the DataOutputStream and FileOutputStream objects.











































































   650   651   652   653   654