There are several problems been faced which are as follows:
- When you write an object in a file using serialization in java for the first time, no problem arises in reading the file afterward, even when you write multiple objects in one go.
- Now, when next time you try to append new objects (of the same type) to that file using serialization, writing the file will be done successfully without any error.
- But, reading the file will create a problem and an exception named as StreamCorruptedException will be thrown.
The root cause behind these problems or we can say the reasons are as follows:
- Whenever we open a file & try to append a serializable object to the end of the file using ObjectOutputStream & FileOutputStream, ObjectOutputStream will write the header to the end of the file to write the object data. Each time when the file gets open and the first object is written, ObjectOutputStream will write the header to the end of the file prior to the writing of object data.
- So, in this way header gets written multiple times whenever the file is opened in append mode to write the object using FileOutputStream & ObjectOutputStream.
In order to fix these issues, several measures are needed to be implemented as follows:
- Create your own Object Output Stream class, say MyObjectOutputStream class, by extending ObjectOutputStream (Inheritance) & Override the method : “protected void writeStreamHeader() throws IOException.” In your new class, this method should do nothing.
- Now when you write Object for the first time, i.e, when file length is 0, use object of Predefined class ObjectOutputStream, to write the object using writeObject().
- This will write the header to the file in the beginning.
Next time whenever you write the object, i.e, when file length is > 0, use the object of Your defined class MyObjectOutputStream, to write the object using writeObject(). As you have overridden the writeStreamHeader() method & it does nothing, the header will not be written again in the file.
Implementation:
Here in order to optimize the program, to get understanding in one go, we will be having 3 different java class files corresponding to their executable java classes
- CustomerCollection.java
- Customer.java
- Main.java
Example 1: CustomerCollection.java
Java
import java.io.*;
import java.util.*;
class MyObjectOutputStream extends ObjectOutputStream {
MyObjectOutputStream() throws IOException
{
super ();
}
MyObjectOutputStream(OutputStream o) throws IOException
{
super (o);
}
public void writeStreamHeader() throws IOException
{
return ;
}
}
public class CustomerCollection {
private static File f = new File( "BankAccountt.txt" );
public static boolean readFile()
{
boolean status = false ;
try {
f.createNewFile();
}
catch (Exception e) {
}
if (f.length() != 0 ) {
try {
FileInputStream fis = null ;
fis = new FileInputStream(
"BankAccountt.txt" );
ObjectInputStream ois
= new ObjectInputStream(fis);
Customer c = null ;
while (fis.available() != 0 ) {
c = (Customer)ois.readObject();
long accNo = c.getAccountNumber();
System.out.println(c.getCustomerName()
+ " & " );
System.out.println(
c.getAccountNumber());
}
ois.close();
fis.close();
status = true ;
}
catch (Exception e) {
System.out.println( "Error Occurred" + e);
e.printStackTrace();
}
}
return status;
}
public static boolean AddNewCustomer(Customer c)
{
boolean status = false ;
if (c != null ) {
try {
FileOutputStream fos = null ;
fos = new FileOutputStream(
"BankAccountt.txt" , true );
if (f.length() == 0 ) {
ObjectOutputStream oos
= new ObjectOutputStream(fos);
oos.writeObject(c);
oos.close();
}
else {
MyObjectOutputStream oos = null ;
oos = new MyObjectOutputStream(fos);
oos.writeObject(c);
oos.close();
}
fos.close();
}
catch (Exception e) {
System.out.println( "Error Occurred" + e);
}
status = true ;
}
return status;
}
}
|
For now, save this code in a file CustomerCollection.java
Example 2: Customer.java
Java
import java.io.*;
class Customer implements Serializable {
private String name;
private long acc_No;
Customer(String n, long id)
{
acc_No = id;
name = n;
}
public String getCustomerName() { return name; }
public long getAccountNumber() { return acc_No; }
}
|
For now, save this code in a file Customer.java
Example 3: Main.java
Java
import java.io.*;
public class Main {
public static void main(String[] args)
{
Customer c1 = new Customer( "Rita" , 1 );
Customer c2 = new Customer( "Sita" , 2 );
CustomerCollection.AddNewCustomer(c1);
CustomerCollection.AddNewCustomer(c2);
System.out.println( "****Reading File****" );
CustomerCollection.readFile();
}
}
|
For now, save this code in a file Main.java
Output: After saving all the 3 files, run the program
Note: Output will be different after the succeeding run trials.
Run 1: When the program is run for the first time the output is as follows:
****Reading File****
Rita & 1
Sita & 2
Run 2: Again when the above program is run, then there is a difference and the output is as follows:
****Reading File****
Rita & 1
Sita & 2
Rita & 1
Sita & 2
Output explanation:
The output is so because already in the first time, these 2 objects (having name Rita & Sita) were written in the file named “BankAccountt.txt” and when you run the code a second time, again the same 2 objects get append in the file.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Feb, 2022
Like Article
Save Article