Java Reference
In-Depth Information
File file
=
null;
// Get the output file name from the argument line.
if (args.length >
0) file
=
new File (args[0]);
// or use a default file name
if (file == null) {
System.out.println ("Default: numerical.dat");
file = new File ("numerical.dat");
}
// Now write the data array to the file.
try {
// Create an output stream to the file.
FileOutputStream fileOutput =
new FileOutputStream (file);
// Wrap the FileOutputStream with a DataOutputStream
DataOutputStream dataOut =
new DataOutputStream (fileOutput);
// Write the data to the file in an integer/
// double pair
for (int i
=
0; i
<
i
-
data.length; i++)
{
dataOut.writeInt (i
-
data[i]);
dataOut.writeDouble (d
-
data[i]);
}
// Close file when finished with it. .
fileOutput.close ();
}
catch (IOException e) {
System.out.println ("IO exception ="+ e);
}
} // main
} // class BinOutputFileApp
9.6.6 Binary input from a file
In the example program below called
BinInputFileApp
,weread a binary file
created by
BinOutputFileApp
discussed in the previous section. We begin
by first opening a stream to the file with a
FileInputStream
object. Then
we wrap this with a
DataInputStream
class to obtain the many
read
X
()
methods, where
X
represents the name of a primitive data type as in
readInt()
and
readDouble()
. Here we read pairs of integer and double values.
Rather than test for the return of a
-1
value as we did in the text input streams,
we simply continue to loop until the read method throws the
EOFException
.In
the
catch
statement for this exception you can carry out the final housekeeping
chores before closing the file stream.
Search WWH ::
Custom Search