Page 653 - Introduction to Programming with Java: A Problem Solving Approach
P. 653
This looks rather like the fileOut = statement in Figure 15.3. The FileOutputStream instantiation here is like the FileWriter instantiation in Figure 15.3 in that it opens the file and implements a buffer. As in Figure 15.3, the second argument says whether to append or overwrite an existing file. This object is different from FileWriter object in that it does not perform any fundamental data-type transformation. It just receives raw bytes or an array of raw bytes, and it passes those bytes on to the file unchanged. The data transformation is done by the DataOutputStream object, which uses one of its write methods to convert primitive data or a string into an appropriate sequence of char’s. To write an individual char, int, double, or String to a file, you could use one of these DataOutputStream methods:
void writeChar(int ch)
void writeInt(int i)
void writeDouble(double x)
void writeChars(String s)
For example, suppose you had an array of double values called doubleValues. In a try block after the above file-opening statement, you could write these values to the binary file using code like this:
for (int i=0; i<doubleValues.length; i++)
{
}
fileOut.writeDouble(doubleValues[i]);
The writeChars method writes a string “as is”—it does not append any line-termination character(s). However, the original String object could include any number of ‘\n’ characters at any places. Thus, you
Apago PDF Enhancer
could refer to a multi-line document with just one String variable, and you could write that whole docu- ment to a binary file with a single for loop that contains just one writeChars statement.
Input
To open a binary file for primitive data input, instantiate a FileInputStream and a DataInputStream like this:8
DataInputStream fileIn;
...
fileIn =
new DataInputStream(new FileInputStream(stdIn.nextLine()));
...
This looks rather like the fileIn = statement in Figure 15.5. The FileInputStream instantiation here is like the FileReader instantiation in Figure 15.5 in that it opens the file and provides a buffer. FileInputStream is different from FileReader object, however, in that it does not perform a data- type transformation. It just receives raw bytes from the file and passes them on. All data transformation is done by the DataInputStream object, which uses one of its read methods to convert the bytes it re- ceives into primitive variables. To read an individual char, int, or double to a file, you could use one of these DataInputStream methods:
8 Optionally, you can speed up execution by inserting a BufferedInputStream object between the DataInputStream and FileInputStream objects.
15.7 Binary File I/O 619