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:
- Serialization in javaJava
- Serialization interview questions and answers
- serialversionuid in java serialization
- externalizable in java
- Transient keyword in java
- Difference between Serializable and Externalizable in Java
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package org.arpit.java2blog; import java.io.Serializable; public class Employee implements Serializable{ private static final long serialVersionUID = 1L; int employeeId; String employeeName; String department; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package org.arpit.java2blog; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializeMain { /** * @author Arpit Mandliya */ public static void main(String[] args) { Employee emp = new Employee(); emp.setEmployeeId(101); emp.setEmployeeName("Arpit"); emp.setDepartment("CS"); try { FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream outStream = new ObjectOutputStream(fileOut); outStream.writeObject(emp); outStream.close(); fileOut.close(); }catch(IOException i) { i.printStackTrace(); } } } |
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