Java Reference
In-Depth Information
The following code creates an output stream and an associated object output stream:
FileOutputStream disk = new FileOutputStream(
“SavedObject.dat”);
ObjectOutputStream disko = new ObjectOutputStream(disk);
The object output stream created in this example is called
disko
. Methods of the
disko
class can be used to write serializable objects and other information to a file called
SavedObject.dat
.
After you have created an object output stream, you can write an object to it by calling
the stream's
writeObject(
Object
)
method.
The following statement calls this method on
disko
, the stream created in the previous
example:
disko.writeObject(userData);
This statement writes an object called
userData
to the
disko
object output stream. The
class represented by
userData
must be serializable for it to work.
An object output stream also can be used to write other types of information with the fol-
lowing methods:
write(
int
)
—Writes the specified integer to the stream, which should be a value
from
0
to
255
.
n
write(
byte[]
)
—Writes the specified byte array.
n
write(
byte[]
,
int
,
int
)
—Writes a subset of the specified byte array. The
second argument specifies the first array element to write, and the last argument
represents the number of subsequent elements to write.
n
writeBoolean(
boolean
)
—Writes the specified
boolean
.
n
writeByte(
int
)
—Writes the specified integer as a byte value.
n
writeBytes(
String
)
—Writes the specified string as a series of bytes.
n
writeChar(
int
)
—Writes the specified character.
n
writeChars(
String
)
—Writes the specified string as a series of characters.
n
writeDouble(
double
)
—Writes the specified
double
.
n
writeFloat(
float
)
—Writes the specified
float
.
n
writeInt(
int
)
—Writes the specified
int
, which unlike the argument to
write(
int
)
can be any
int
value.
n
writeLong(
long
)
—Writes the specified
long
.
n
writeShort(
short
)
—Writes the specified
short
.
n