read Object Java


Write and read Object Java to a file is given with Example is given in Simple terms.

We have seen earlier how to create an object using cloning and newInstance() method. Now let us try another way using the concept serialization. It is a round about process; I do not like it personally. My aim is to show there exists a way to create an object without new keyword using serialization.

It is only coding importance, nobody follows this style to create an object without new keyword. The best way is cloning. Serialization is used to write an object to file or sending the object across network.

Example on write object and read object Java
import java.io.*;
class Test implements Serializable
{
  int x;
}

public class Demo
{
  public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException
  {     
                                 // first, write an object t1 to file abc.txt         
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("abc.txt"));        
    Test t1 = new Test();
    t1.x = 100;
    oos.writeObject(t1);
    oos.close();                                                                        
                                 // then, read an object from file abc.txt                                                                                                   
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("abc.txt"));    
    Object obj =  ois.readObject();
    Test t2 = (Test) obj;
    ois.close();
    System.out.println(t1.x);    // prints 100
  }
}

First, let me say sorry as I feel it is not the proper place to explain serialization and deserialization. What I would like to say is until and unless you know the serialization concept, you do not understand code.

I explain briefly. Using ObjectOutputStream object oos, the object t1 of Test class is written to a file abc.txt. Then using ObjectInputStream method readObject(), the Test object is read from abc.txt file. The readOject() method returns an object of Object class and is type casted to Test class. The emphasis is that we are not using new keyword to create an object t2. But do not say that I have used new keyword while creating t1.

Serialization is given clearly in What is Serialization in Java?

Would you like to know all the 5 styles of creating Java object without using new keyword?

Leave a Comment

Your email address will not be published.