- All Implemented Interfaces:
Closeable,DataOutput,Flushable,ObjectOutput,ObjectStreamConstants,AutoCloseable
Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.
The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.
Primitive data types can also be written to the stream using the appropriate methods from DataOutput. Strings can also be written using the writeUTF method.
The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.
For example to write an object that can be read by the example in ObjectInputStream
:
try (FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject("Today");
oos.writeObject(LocalDateTime.now());
} catch (Exception ex) {
// handle exception
}
Serializable classes that require special handling during the serialization and deserialization process should implement methods with the following signatures:
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException;
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException;
private void readObjectNoData()
throws ObjectStreamException;
The method name, modifiers, return type, and number and type of parameters must match exactly for the method to be used by serialization or deserialization. The methods should only be declared to throw checked exceptions consistent with these signatures.
The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object's superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.
Serialization does not write out the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state.
Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process.
Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.
Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not transmitted. To serialize an enum constant, ObjectOutputStream writes the string returned by the constant's name method. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream. The process by which enum constants are serialized cannot be customized; any class-specific writeObject and writeReplace methods defined by enum types are ignored during serialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L.
Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. Consecutive primitive data writes are merged into one block-data record. The blocking factor used for a block-data record will be 1024 bytes. Each block-data record will be filled up to 1024 bytes, or be written whenever there is a termination of block-data mode. Calls to the ObjectOutputStream methods writeObject, defaultWriteObject and writeFields initially terminate any existing block-data record.
Records are serialized differently than ordinary serializable or externalizable objects, see record serialization.
- Since:
- 1.1
- External Specifications
- See Also:
Nested Types
- ✓ PutField
Constructors
- ✓protected ObjectOutputStream() throws java.io.IOException, java.lang.SecurityException
- ✓public ObjectOutputStream(java.io.OutputStream arg0) throws java.io.IOException
Methods
- ✓protected void annotateClass(java.lang.Class<?> arg0) throws java.io.IOException
- ✓protected void annotateProxyClass(java.lang.Class<?> arg0) throws java.io.IOException
- ✓public void close() throws java.io.IOException
- ✓public void defaultWriteObject() throws java.io.IOException
- ✓protected void drain() throws java.io.IOException
- ✓protected boolean enableReplaceObject(boolean arg0) throws java.lang.SecurityException
- ✓public void flush() throws java.io.IOException
- ✓public java.io.ObjectOutputStream.PutField putFields() throws java.io.IOException
- ✗protected java.lang.Object replaceObject(java.lang.Object arg0) throws java.io.IOExceptionComparing jdk-20-ga and jdk-21+35
replaceObject
This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization. Replacing objects is disabled until enableReplaceObject is called. The enableReplaceObject method checks that the stream requesting to do replacement can be trusted. The first occurrence of each object written into the serialization stream is passed to replaceObject. Subsequent references to the object are replaced by the object returned by the original call to replaceObject. To ensure that the private state of objects is not unintentionally exposed, only trusted streams may use replaceObject.The ObjectOutputStream.writeObject method takes a parameter of type Object (as opposed to type Serializable) to allow for cases where non-serializable objects are replaced by serializable ones.
When a subclass is replacing objects it must ensure that either a complementary substitution must be made during deserialization or that the substituted object is compatible with every field where the reference will be stored. Objects whose type is not a subclass of the type of the field or array element abort the serialization by raising an exception and the object is not be stored.
This method is called only once when each object is first encountered. All subsequent references to the object will be redirected to the new object. This method should return the object to be substituted or the original object.
Null can be returned as the object to be substituted, but may cause NullReferenceException
NullPointerExceptionin classes that contain references to the original object since they may be expecting an object instead of null.- Parameters:
obj- the object to be replaced- Returns:
- the alternate object that replaced the specified one
- Throws:
IOException- Any exception thrown by the underlying OutputStream.
- ✓public void reset() throws java.io.IOException
- ✓public void useProtocolVersion(int arg0) throws java.io.IOException
- ✓public void write(int arg0) throws java.io.IOException
- ✓public void write(byte[] arg0) throws java.io.IOException
- ✓public void write(byte[] arg0, int arg1, int arg2) throws java.io.IOException
- ✓public void writeBoolean(boolean arg0) throws java.io.IOException
- ✗public void writeByte(int arg0) throws java.io.IOExceptionComparing jdk-20-ga and jdk-21+35
writeByte
Writes an 8-bit byte.- Specified by:
writeBytein interfaceDataOutput- Parameters:
val- the byte value to be written- Throws:
IOException- if I/O errors occur while writing to the underlying stream
- ✓public void writeBytes(java.lang.String arg0) throws java.io.IOException
- ✗public void writeChar(int arg0) throws java.io.IOExceptionComparing jdk-20-ga and jdk-21+35
writeChar
Writes a 16-bit char.- Specified by:
writeCharin interfaceDataOutput- Parameters:
val- the char value to be written- Throws:
IOException- if I/O errors occur while writing to the underlying stream
- ✓public void writeChars(java.lang.String arg0) throws java.io.IOException
- ✗protected void writeClassDescriptor(java.io.ObjectStreamClass arg0) throws java.io.IOExceptionComparing jdk-20-ga and jdk-21+35
writeClassDescriptor
Write the specified class descriptor to the ObjectOutputStream. Class descriptors are used to identify the classes of objects written to the stream. Subclasses of ObjectOutputStream may override this method to customize the way in which class descriptors are written to the serialization stream. The corresponding method in ObjectInputStream,readClassDescriptor, should then be overridden to reconstitute the class descriptor from its custom stream representation. By default, this method writes class descriptors according to the format defined in the Java Object Serialization Specification .Note that this method will only be called if the ObjectOutputStream is not using the old serialization stream format (set by calling ObjectOutputStream's
useProtocolVersionmethod). If this serialization stream is using the old format (PROTOCOL_VERSION_1), the class descriptor will be written internally in a manner that cannot be overridden or customized.- Parameters:
desc- class descriptor to write to the stream- Throws:
IOException- If an I/O error has occurred.- Since:
- 1.3
- External Specifications
- See Also:
- ✗public void writeDouble(double arg0) throws java.io.IOExceptionComparing jdk-20-ga and jdk-21+35
writeDouble
Writes a 64-bit double.- Specified by:
writeDoublein interfaceDataOutput- Parameters:
val- the double value to be written- Throws:
IOException- if I/O errors occur while writing to the underlying stream
- ✓public void writeFields() throws java.io.IOException
- ✗public void writeFloat(float arg0) throws java.io.IOExceptionComparing jdk-20-ga and jdk-21+35
writeFloat
Writes a 32-bit float.- Specified by:
writeFloatin interfaceDataOutput- Parameters:
val- the float value to be written- Throws:
IOException- if I/O errors occur while writing to the underlying stream
- ✗public void writeInt(int arg0) throws java.io.IOExceptionComparing jdk-20-ga and jdk-21+35
writeInt
Writes a 32-bit int.- Specified by:
writeIntin interfaceDataOutput- Parameters:
val- the integer value to be written- Throws:
IOException- if I/O errors occur while writing to the underlying stream
- ✗public void writeLong(long arg0) throws java.io.IOExceptionComparing jdk-20-ga and jdk-21+35
writeLong
Writes a 64-bit long.- Specified by:
writeLongin interfaceDataOutput- Parameters:
val- the long value to be written- Throws:
IOException- if I/O errors occur while writing to the underlying stream
- ✓public final void writeObject(java.lang.Object arg0) throws java.io.IOException
- ✓protected void writeObjectOverride(java.lang.Object arg0) throws java.io.IOException
- ✗public void writeShort(int arg0) throws java.io.IOExceptionComparing jdk-20-ga and jdk-21+35
writeShort
Writes a 16-bit short.- Specified by:
writeShortin interfaceDataOutput- Parameters:
val- the short value to be written- Throws:
IOException- if I/O errors occur while writing to the underlying stream
- ✓protected void writeStreamHeader() throws java.io.IOException
- ✓public void writeUTF(java.lang.String arg0) throws java.io.IOException
Summary
| Elements | Comments | Descriptions | Total | |||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Added | Changed | Removed | Added | Changed | Removed | Added | Changed | Removed | ||
| ObjectOutputStream | 3 | 3 | ||||||||
| replaceObject(Object) | 1 | 1 | 2 | |||||||
| writeByte(int) | 1 | 1 | ||||||||
| writeChar(int) | 1 | 1 | ||||||||
| writeClassDescriptor(ObjectStreamClass) | 3 | 3 | ||||||||
| writeDouble(double) | 1 | 1 | ||||||||
| writeFloat(float) | 1 | 1 | ||||||||
| writeInt(int) | 1 | 1 | ||||||||
| writeLong(long) | 1 | 1 | ||||||||
| writeShort(int) | 1 | 1 | ||||||||
| Total | 14 | 1 | 15 | |||||||