Page 637 - Introduction to Programming with Java: A Problem Solving Approach
P. 637
15.2 Java API Classes You Need to Import 603
Text file I/O. For primitive data. Easy to understand.
Computer transforms primitive data from native format into readable text format for files. You can create or view text files with almost any text editor.
for output to a text file:
PrintWriter
FileWriter
for input from a text file:
Scanner
FileReader
Binary file I/O. For primitive data. Efficient.
Files get primitive data in native format.
You cannot create or view binary files with a text editor, but binary files are very compact.
for output to a binary file:
DataOutputStream
FileOutputStream
for input from a binary file:
DataInputStream
FileInputStream
Object file I/O. For complete objects. Easy to use.
Apago PDF Enhancer
Computer decomposes objects into primitive data for files, which also get descriptive headers. You cannot create or view object files with a text editor, but your coding is minimized.
for output to an object file:
ObjectOutputStream
FileOutputStream
for input from an object file:
ObjectInputStream
FileInputStream
<same as for binary output> <same as for binary input>
Figure 15.1 Classes we recommend using for file I/O
The Scanner class is in the java.util package. The others are in the java.io package.
The simplest way to store text and/or text representations of numbers is in text files. In text files, everything is represented in terms of ASCII characters, which we described in Chapter 11. As shown in Figure 11.4, each ASCII character is coded in an eight-bit sequence of 0’s and 1’s. We’ll discuss this coding scheme in more depth later in this chapter, in Section 15.6. To write text to a text file, we recommend that you use the PrintWriter class, which has println, print, and printf, methods. Those methods parallel the same-named methods that you’ve called from System.out for quite a while. The System. out methods print to the computer monitor. The PrintWriter methods print to a file. To read text from a text file, we recommend that you use the Scanner class, which has the nextLine, next, nextInt, nextLong, nextFloat, and nextDouble methods that you’ve used for quite a while. But now you’ll use those methods to get input from a file rather than from a keyboard. The Scanner class works in con- junction with the FileReader class. You instantiate the Scanner constructor with a FileReader