Java Reference
In-Depth Information
The output of reading the file then looks like:
Skip strings at start of textOutput.txt
and then read the primitive type values:
boolean
=
false
int
=
114
int
=
1211
int
=
1234567
long
=
987654321
float
=
983.6
double
=
-4.30e-15
9.6.5 Binary output to a file
Numerical data transfers faster and more compactly in a raw binary format than
as text characters. Here we look at examples of writing numerical data to a binary
file and reading numerical data from a binary file.
In the example program below called BinOutputFileApp ,wefirst create
some data arrays with some arbitrary values. We then open a stream to a file
with the binary FileOutputStream class. We wrap this stream object with an
instance of the DataOutputStream class, which contains many useful methods
for writing primitive types of the writeX() form, where X is the name of a prim-
itive type. We use the writeInt (int i) and the writeDouble (double
d) methods, to write the data to the file as pairs of int/double type values.
In the next section we will show next how to read the binary data from this file.
import java.io.*;
import java.util.*;
/** Write a primitive type data array to a binary file. **/
public class BinOutputFileApp
{
public static void main (String[] args) {
Random ran = new Random ();
// Create an integer array and a double array.
int []i - data = new int[15];
double [] d - data = new double[15];
// and fill them
for (int i=0; i < i - data.length; i++) {
i - data[i] = i;
d - data[i] = ran.nextDouble() * 10.0;
}
Search WWH ::




Custom Search