Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Example Java Io Java ObjectOutputStream

Related Tutorials


 
 

Share on Google+Share on Google+

Java ObjectOutputStream

Advertisement
In this tutorial we will discuss about the Java class ObjectOutputStream.

Java ObjectOutputStream

In this tutorial we will discuss about the Java class ObjectOutputStream.

java.io.ObjectOutputStream class is used to write the primitive data types and the graphs of Java objects to the output stream. It writes only those objects to the stream which implements the java.io.Serializable interface. To write the primitive data types to the stream methods of DataOutput can be used. writeObject method can write any object to the stream whether the objects are String or arrays. To read the objects written into the output stream a corresponding ObjectInputStream class is used with the same types and order in which they are written.

Constructors of ObjectOutuptStream

Constructor Name
Description
ObjectOutputStream() This is a default constructor which is implemented by the subclasses in a way to not have to allocate private data.
Syntax : protected ObjectOutputStream() throws IOException, SecurityException
ObjectOutputStream(OutputStream out) This is a parameterized constructor which is used to create an object of ObjectOutputStream that contains the reference of OutputStream where the data to be written.
Syntax :public ObjectOutputStream(OutputStream out) throws IOException

Methods of ObjectOutputStream

Commonly used methods of ObjectOutputStream

  • writeObject(Object obj) : This method is used to write the object to the output stream.

    Syntax : public final void writeObject(Object obj) throws IOException
     
  • close() : This method is used to close the streams and is called for releasing the resources associated with the stream.

    Syntax : public void close() throws IOException
     
  • flush() : This method is used to flush the stream.

    Syntax : public void flush() throws IOException
     
  • replaceObject(Object obj) : This method is used to replace the one object with another when serializing the object.

    Syntax : protected Object replaceObject(Object obj) throws IOException
     
  • reset() : This method is used to reset all the objects which are already written to the stream.

    Syntax : public void reset() throws IOException
     
  • write(byte[] buf) : This method is used to write an array of bytes to the output stream.

    Syntax : public void write(byte[] buf) throws IOException
     
  • write(byte[] buf, int off, int len) : This method is used to write a specified length of bytes of a specified array started from the offset 'off'.

    Syntax : public void write(byte[] buf, int off, int len) throws IOException
     
  • write(int val) : This method is used to write a byte to the output stream.

    Syntax : public void write(int val) throws IOException
     
  • writeBoolean(boolean val) : This method is used to write boolean to the output stream.

    Syntax : public void writeBoolean(boolean val) throws IOException
     
  • writeByte(int val) : This method is used to write 8 bit byte to the output stream.

    Syntax : public void writeByte(int val) throws IOException
     
  • writeBytes(String str) : This method is used to write string as a sequence of bytes to the output stream.

    Syntax : public void writeBytes(String str) throws IOException
     
  • writeChar(int val) : This method is used to write 16 bit char to the output stream.

    Syntax : public void writeChar(int val) throws IOException
     
  • writeChars(String str) : This method is used to write string as a sequence of char to the output stream.

    Syntax : public void writeChars(String str) throws IOException
     
  • writeDouble(double val) : This method is used to write 64 bit double to the output stream.

    Syntax : public void writeDouble(double val) throws IOException
     
  • writeFloat(float val) : This method is used to write 32 bit float to the output stream.

    Syntax : public void writeFloat(float val) throws IOException
     
  • writeInt(int val) : This method is used to write a 32 bit int to the output stream.

    Syntax : public void writeInt(int val) throws IOException
     
  • writeLong(long val) : This method is used to write a 64 bit long to the output stream.

    Syntax : public void writeLong(long val) throws IOException
     
  • writeShort(int val) : This method is used to write a 16 bit short to the output stream.

    Syntax : public void writeShort(int val) throws IOException
     
  • writeUTF(String str) : This method is used to write the string in modified UTF-8 format.

    Syntax : public void writeUTF(String str) throws IOException

Example

An example is being given here which will demonstrate you about how to use the ObjectOutuptStream class to write the object to the output stream. In this example at first I have created a Java class which writes the objects to the output stream then created a corresponding Java class which will read the objects from the stream.

Source Code

ObjectOutputStreamExample.java

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

public class ObjectOutputStreamExample
{
    public static void main(String args[])
     {
        
        ObjectOutputStream oos = null;
        
        try
          {
             FileOutputStream fos = new FileOutputStream("employee.txt");
            
             oos = new ObjectOutputStream(fos);
             
             oos.writeObject("Shashi");
             oos.writeObject("Content Writer");
             oos.writeInt(20000);

             oos.writeObject("Amit");
             oos.writeObject("Content Writer");
             oos.writeInt(18000);
            
            System.out.println();
            System.out.println("objects written successfully");
        }
     catch (FileNotFoundException fex)
       {
            System.out.println(fex);
       }
     catch (Exception ex)
      {
            System.out.println(ex);
      }
     finally
      {
          try
           {
                if (oos != null)
                 {
                     oos.close();
                 }
            }
         catch (Exception ex1)
           {
                System.out.println(ex1);
            }
       }
    }       
}

ReadObjectInputStream.java

import java.io.*;

public class ReadObjectInputStream
{    
    public static void main(String args[])
     {
        
        ObjectInputStream ois = null;
        
        try
          {
             FileInputStream fis = new FileInputStream("employee.txt");
             ois = new ObjectInputStream(fis);
            
             String sh = (String) ois.readObject();
             String cw = (String) ois.readObject();
             int      sal = ois.readInt();
             
             String am = (String) ois.readObject();
             String cw1 = (String) ois.readObject();
             int      sal1 = ois.readInt();
             System.out.println();
             System.out.println("Name \t"+"Department \t"+"Salary");
             System.out.println(sh+"\t"+cw+"\t"+sal);
             System.out.println(am+"\t"+cw1+"\t"+sal1);             
         
          }
       catch (EOFException ex)
         {
           //This exception will be caught when EOF is reached
            System.out.println("End of file reached.");
         }
       catch (ClassNotFoundException ex)
        {
            System.out.println(ex);
        }
       catch (Exception ex)
        {
            System.out.println(ex);
        }
       finally
        {
            try 
              {
                  if (ois != null)
                   {
                      ois.close();
                   }
              }
            catch (Exception ex) 
              {
                  System.out.println(ex);
              }
         }
    }
}

Output

First compile and execute the ObjectOutputStreamExample.java which will write the objects to the output stream as follows :

Then Compile and execute the ReadObjectInputStream.java which will read the objects written to the output stream then the output will be as follows :

Download Source Code

 

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 12, 2012

Related Tutorials

Discuss: Java ObjectOutputStream  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com