Java Reference
In-Depth Information
You can write a string object to the file as a sequence of bytes using the writeBytes() method,
passing a reference to a String as the argument to the method. Each character in the string is
converted to a byte using the default charset. To write a string as a sequence of Unicode characters, you
use the writeChars() method, again with a reference of type String as the argument. This writes
each Unicode character in the string as two bytes. Note that these methods write just a sequence of
bytes or characters. No information about the original String object is written so the fact that these
characters belonged to a string is lost. If you want to write a String object to the file as an object, use
the writeObject() method.
You have two methods that apply to arrays of bytes. These override the methods inherited from
InputStream :
Write(byte[] array)
Writes the contents of array to the file as bytes.
Write(byte[] array,
int offset,
Writes length elements from array to the file starting
with array[offset] .
int length)
In both cases just bytes are written to the stream as binary data, not the array object itself. An array of
type byte[] will be written to the stream as an object by default, so you will only need to use these
methods if you do not want an array of type byte[] written as an object.
You can mix writing data of the basic types and class objects to the stream. If you have a mixture of
objects and data items of basic types that you want to store in a file, you can write them all to the same
ObjectOutputStream . You just have to make sure that you read everything back in the sequence
and form that it was written.
Implementing the Serializable Interface
A necessary condition for objects of a class to be serializable is that the class implements the
Serializable interface but this may not be sufficient, as we shall see. In most instances, you need
only declare that the class implements the Serializable interface to make the objects of that class
type serializable. No other code is necessary. For example, the following declares a class that
implements the interface.
public MyClass implements Serializable {
// Definition of the class...
}
If your class is derived from another class that implements the Serializable interface, then your
class also implements Serializable so you don't have to declare that this is the case. Let's try this out
on a simple class to verify that it really works.
Search WWH ::




Custom Search