Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to write Object into a file .

Java Code Example — File Handling Programs

ADVERTISEMENT

Java Program to write Object into a file .

Objective

Write a Java program to serialize (write) a custom Object into a file.

Algorithm / Approach

  1. Create a custom class Test and append implements Serializable to its signature.
  2. In the main writer class, open a FileOutputStream.
  3. Wrap it in an ObjectOutputStream.
  4. Instantiate a Test object with data.
  5. Write the object to the file using oos.writeObject(t).
  6. 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.Serializable interface. 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)
ADVERTISEMENT