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

                storage to create a text file that a Java program can read. You can use a word processor to read any text
file written by a Java program.
• The data in a binary file appears as a sequence of data items, each encoded in the computer’s native
format for that type of data. You cannot create or read binary files with text editors or word processors. However, binary files can store a much greater variety of characters, and they can store high-precision numbers more efficiently.
• To output (or input) primitives to (or from) a binary file, open the file by instantiating a DataOutputStream (or DataInputStream) object with an anonymous FileOutputStream (or FileInputStream) object as the constructor argument. Use the filename for the FileOutputStream (or FileInputStream) argument. Then use methods like writeInt or readInt to write or read primitive values.
• You can store whole objects in a file in binary format, provided those objects and all their component objects implement the Serializable interface.
• To output (or input) objects to a file, open the file by instantiating an ObjectOutputStream (or ObjectInputStream) object with an anonymous FileOutputStream (or FileInputStream) object as the constructor argument. Use the filename for the FileOutputStream (or FileInputStream) constructor argument. Then use writeObject and readObject methods to transfer complete objects to and from the file.
• The File class manipulates whole files and describes their environments.
• Optionally, with Java’s JFileChooser class, you can enable a user of one of your programs to find
any file in his or her computer by interacting with a familiar graphical user interface.
          Apago PDF Enhancer
Review Questions
§15.2 Java API Classes You Need to Import
1. You can create or view the contents of binary or object files with many text editors. (T / F)
2. Write an import statement that provides access to any of the classes in the java.io package.
§15.3 Text-File Output
3. What are the three basic steps to performing file I/O?
4. Using a PrintWriter method, write a Java statement that outputs a String called name followed by a
space and an int called id, so that a later file-input nextLine operation will recognize the combination
as a distinct string.
5. Write a single statement that opens an existing text file called mydata.txt for output, such that new
output data is appended to the data already in the file.
§15.4 Text-File Input
6. Assuming fileName is a String that correctly identifies a text file in the current directory, what’s
wrong with this file-opening statement?
Scanner fileReader = new Scanner(fileName);
7. Assume you have a text file with these two lines of data:
55.6 hi
Review Questions 635
 there





































































   667   668   669   670   671