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.
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
packageorg.arpit.java2blog;
import java.io.Serializable;
publicclassEmployeeimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
intemployeeId;
StringemployeeName;
Stringdepartment;
publicintgetEmployeeId(){
returnemployeeId;
}
publicvoidsetEmployeeId(intemployeeId){
this.employeeId=employeeId;
}
publicStringgetEmployeeName(){
returnemployeeName;
}
publicvoidsetEmployeeName(StringemployeeName){
this.employeeName=employeeName;
}
publicStringgetDepartment(){
returndepartment;
}
publicvoidsetDepartment(Stringdepartment){
this.department=department;
}
}
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
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
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.