How to write object to a file in java

Previous
Next

If you want to send object over network, then you need to  write object to a file and convert it to the stream. This process can be referred as serialization.

Object needs to implement Serializable interface which is marker interface  interface and we will use java.io.ObjectOutputStream to write object to a file.

Java Serialization Tutorial:

Lets go through steps for writing object to a file.


Lets take an example:
Create Employee.java in src->org.arpit.java2blog

1.Employee.java

As you can see above,if you want to serialize any class then it must implement Serializable interface which is marker interface.
Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface
Create SerializeMain.java in src->org.arpit.java2blog
2.SerializeMain.java

When you run above program,employee.ser will get created. Its content won’t be in human readable format but it will have object stored on file . You can use ObjectInputStream to read same object from file.

These are some simple steps to write object to a file. If you want to go through some complex scenario you can go through Serialization in java

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog