Java Reference
In-Depth Information
sequence of bytes (same sequence of zeros and ones) whether it is stored in an
int
vari-
able in memory or in a binary file. So, no conversion of any kind needs to be per-
formed when you store or retrieve a value in a binary file. This is why binary files can
be handled more efficiently than text files.
Java binary files are unlike binary files in other programming languages in that they
are portable. A binary file created by a Java program can be moved from one computer
to another and still be read by a Java program—but only by a Java program. They can-
not normally be read with a text editor or with a program written in any programming
language other than Java.
The preferred stream classes for processing binary files are
ObjectInputStream
and
ObjectOutputStream
. Each has methods to read or write data one byte at a time. These
streams can also automatically convert numbers and characters to bytes that can be stored
in a binary file. They allow your program to be written as if the data placed in the file, or
read from the file, were not just bytes but were strings or items of any of Java's primitive
data types, such as
int
,
char
, and
double
, or even objects of classes you define. If you do
not need to access your files using an editor, then the easiest and most efficient way to read
data from and write data to files is to use binary files in the way we describe here.
We conclude this section with a discussion of how you can use
ObjectOutput-
Stream
and
ObjectInputStream
to write and later read objects of any class you define.
This will let you store objects of the classes you define in binary files and later read
them back, all with the same convenience and efficiency that you get when storing
strings and primitive type data in binary files.
Writing Simple Data to a Binary File
The class
ObjectOutputStream
is the preferred stream class for writing to a binary
file.
2
An object of the class
ObjectOutputStream
has methods to write strings and val-
ues of any of the primitive types to a binary file. Display 10.13 shows a sample pro-
gram that writes values of type
int
to a binary file. Display 10.14 describes the
methods used for writing data of other types to a binary file.
Display 10.13
Writing to a Binary File
(part 1 of 2)
1
import
java.io.ObjectOutputStream;
2
import
java.io.FileOutputStream;
3
import
java.io.IOException;
4
public
class
BinaryOutputDemo
5{
6
public
static
void
main(String[] args)
7
{
(continued)
2
DataOutputStream
is also widely used and behaves exactly as we describe for
ObjectOutputStream
in this section. However, the techniques given in the subsections “Binary I/O of Objects” and “Array
Objects in Binary Files” only work for
ObjectOutputStream
; they do not work for
DataOutputStream
.