Java Program to write Object into a file .
Objective
Write a Java program to serialize (write) a custom Object into a file.
Algorithm / Approach
- Create a custom class
Testand appendimplements Serializableto its signature. - In the main writer class, open a
FileOutputStream. - Wrap it in an
ObjectOutputStream. - Instantiate a
Testobject with data. - Write the object to the file using
oos.writeObject(t). - Close the streams.
Test.java
//File 1: Test.java
import java.io.*;
class Test implements Serializable{
String name;
int age;
Test(String n, int a){
name = n;
age = a;
}
void display() {
System.out.println("Name: "+name);
System.out.println("Age: "+age);
}
}
//File 2: WriteObject.java
import java.io.*;
class WriteObject {
void writeObj() {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
String file="Alok.txt";
try {
fos=new FileOutputStream(file);
oos=new ObjectOutputStream(fos);
Test t =new Test("Alok",24);
oos.writeObject(t);
System.out.print("Object Written");
}
catch(Exception e) {
System.out.print(e);
}
finally{
try {
fos.close();
oos.close();
}
catch(Exception e) {
System.out.print(e);
}
}
}
public static void main(String[] a)
{
WriteObject ob= new WriteObject();
ob.writeObj();
}
}
Expected Output
Object Written
Explanation of the Program
- Serialization is the process of converting the state of a Java object into a byte stream so it can be saved to a database, sent over a network, or saved to a file.
- To allow an object to be serialized, its class MUST implement the
java.io.Serializableinterface. This is a "marker interface" (it has no methods). It simply flags the class to the JVM, giving it permission to flatten the object into bytes. - If you attempt to serialize an object that does not implement
Serializable, an exception will be thrown.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)