Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java - ObjectOutputStream class



Introduction

The Java ObjectOutputStream class writes primitive data types and graphs of Java objects to an OutputStream.The objects can be read (reconstituted) using an ObjectInputStream.

Class declaration

Following is the declaration for Java.io.ObjectOutputStream class −

public class ObjectOutputStream
   extends OutputStream
      implements ObjectOutput, ObjectStreamConstants

Class constructors

Sr.No. Constructor & Description
1

protected ObjectOutputStream()

This provides a way for subclasses that are completely reimplementing ObjectOutputStream to not have to allocate private data just used by this implementation of ObjectOutputStream.

2

ObjectOutputStream(OutputStream out)

This creates an ObjectOutputStream that writes to the specified OutputStream.

Class methods

Sr.No. Method & Description
1 protected void annotateClass(Class <?> cl)

Subclasses may implement this method to allow class data to be stored in the stream.

2 protected void annotateProxyClass(Class<?> cl)

Subclasses may implement this method to store custom data in the stream along with descriptors for dynamic proxy classes.

3 void close()

This method closes the stream.

4 void defaultWriteObject()

This method writes the non-static and non-transient fields of the current class to this stream.

5 protected void drain()

This method drain any buffered data in ObjectOutputStream.

6 protected boolean enableReplaceObject(boolean enable)

This method enable the stream to do replacement of objects in the stream.

7 void flush()

This method flushes the stream.

8 ObjectOutputStream.PutField putFields()

This method retrieves the object used to buffer persistent fields to be written to the stream.

9 protected Object replaceObject(Object obj)

This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization.

10 void reset()

This method reset will disregard the state of any objects already written to the stream.

11 void useProtocolVersion(int version)

This method specify stream protocol version to use when writing the stream.

12 void write(byte[] buf)

This method writes an array of bytes.

13 void write(byte[] buf, int off, int len)

This method writes a sub array of bytes.

14 void write(int val)

This method writes a byte.

15 void writeBoolean(boolean val)

This method writes a boolean.

16 void writeByte(int val)

This method writes an 8 bit byte.

17 void writeBytes(String str)

This method writes a String as a sequence of bytes.

18 void writeChar(int val)

This method writes a 16 bit char.

19 void writeChars(String str)

This method writes a String as a sequence of chars.

20 protected void writeClassDescriptor(ObjectStreamClass desc)

This method writes the specified class descriptor to the ObjectOutputStream.

21 void writeDouble(double val)

This method writes a 64 bit double.

22 void writeFields()

This method writes the buffered fields to the stream.

23 void writeFloat(float val)

This method writes a 32 bit float.

24 void writeInt(int val)

This method writes a 32 bit int.

25 void writeLong(long val)

This method writes a 64 bit long.

26 void writeObject(Object obj)

This method writes the specified object to the ObjectOutputStream.

27 protected void writeObjectOverride(Object obj)

This method is used by subclasses to override the default writeObject method.

28 void writeShort(int val)

This method writes a 16 bit short.

29 protected void writeStreamHeader()

This method is provided so subclasses can append or prepend their own header to the stream.

30 void writeUnshared(Object obj)

This method writes an "unshared" object to the ObjectOutputStream.

Methods inherited

This class inherits methods from the following classes −

  • Java.io.Object

Example - Properly closing ObjectOutputStream

The following example shows the usage of ObjectOutputStream close() method. We're properly closing ObjectOutputStream after writing an object.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      String filename = "person1.ser";

      try {
         FileOutputStream fos = new FileOutputStream(filename);
         ObjectOutputStream oos = new ObjectOutputStream(fos);

         Person person = new Person("Alice", 30);
         oos.writeObject(person);

         // Close the stream
         oos.close();
         System.out.println("ObjectOutputStream closed after writing object.");
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   static class Person implements Serializable {
      String name;
      int age;
      Person(String name, int age) {
         this.name = name;
         this.age = age;
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

ObjectOutputStream closed after writing object.

Explanation

  • We're serializing a Person object and explicitly calls close() on the ObjectOutputStream.

  • Closing the stream flushes the data and releases system resources.

Example - Usage of ObjectOutputStream defaultWriteObject() method

The following example shows the usage of ObjectOutputStream defaultWriteObject() method.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) throws Exception {
      String file = "user1.ser";

      // Serialize the object
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
         User user = new User("Alice", "secret123");
         oos.writeObject(user);
      }

      System.out.println("User object serialized.");
   }

   static class User implements Serializable {
      private static final long serialVersionUID = 1L;

      String username;
      transient String password; // transient field won't be serialized by default

      User(String username, String password) {
         this.username = username;
         this.password = password;
      }

      // Custom serialization
      private void writeObject(ObjectOutputStream oos) throws IOException {
         oos.defaultWriteObject(); // writes non-transient fields
         oos.writeUTF(password);   // manually write the transient field
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

User object serialized.

Explanation

  • username is serialized normally via defaultWriteObject().

  • password is transient, so we manually write it after.

Example - Using drain() method before writing a second object

The following example shows the usage of ObjectOutputStream drain() method. We're writing multiple objects to a file then using drain() method between them to ensure any buffered data is cleared before writing the next one.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class ObjectOutputStreamDemo extends ObjectOutputStream {

   public ObjectOutputStreamDemo(OutputStream out) throws IOException {
      super(out);
   }

   public static void main(String[] args) {
      String filename = "drain_multiple_objects.ser";

      try (FileOutputStream fos = new FileOutputStream(filename);
         ObjectOutputStreamDemo oos = new ObjectOutputStreamDemo(fos)) {

         // Write first object
         oos.writeObject("First object");
         System.out.println("First object written.");

         // Drain buffered data (but do not flush underlying stream)
         oos.drain();
         System.out.println("Buffer drained.");

         // Write second object
         oos.writeObject("Second object");
         System.out.println("Second object written.");

      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

First object written.
Buffer drained.
Second object written.

Explanation

  • We subclass ObjectOutputStream to access the protected drain() method.

  • We write "First object", then call drain() - this flushes the internal buffer only, not the file stream.

  • Then we write "Second object".

Advertisements