How to Fix java.io.StreamCorruptedException: invalid type code in Java?
Last Updated :
08 Feb, 2022
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
// Java program to illustrate CustomerCollection.java
// Importing input output classes
import java.io.*;
// Importing utility classes
import java.util.*;
// Class 1
// helper class
class MyObjectOutputStream extends ObjectOutputStream {
// Constructor of this class
// 1. Default
MyObjectOutputStream() throws IOException
{
// Super keyword refers to parent class instance
super();
}
// Constructor of this class
// 1. Parameterized constructor
MyObjectOutputStream(OutputStream o) throws IOException
{
super(o);
}
// Method of this class
public void writeStreamHeader() throws IOException
{
return;
}
}
// Class 2
// Helper class
public class CustomerCollection {
// Getting file from local machine by creating
// object of File class
private static File f = new File("BankAccountt.txt");
// Method 1
// To read from the file
public static boolean readFile()
{
// Initially setting bool value as false
boolean status = false;
// Try block to check for exceptions
try {
// Creating new file using File object above
f.createNewFile();
}
// Catch block to handle the exception
catch (Exception e) {
}
// If the file is empty
if (f.length() != 0) {
try {
// If file doesn't exists
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();
// Print customer name and account
// number
System.out.println(c.getCustomerName()
+ " & ");
System.out.println(
c.getAccountNumber());
}
// Closing the connection to release memory
// resources using close() method
ois.close();
fis.close();
// Once all connection are closed after the
// desired action change the flag state
status = true;
}
// Catch block to handle the exception
catch (Exception e) {
// Print the exception on the console
// along with display message
System.out.println("Error Occurred" + e);
// Exception encountered line is also
// displayed on console using the
// printStackTrace() method
e.printStackTrace();
}
}
return status;
}
// Method 2
// To add a new customer
public static boolean AddNewCustomer(Customer c)
{
// again, setting and initializing the flag boolean
// value
boolean status = false;
// If customer is not present
if (c != null) {
// try block to check for exception
try {
// Initially assigning the object null to
// avoid GC involvement
FileOutputStream fos = null;
// Creating an new FileOutputStream object
fos = new FileOutputStream(
"BankAccountt.txt", true);
// If there is nothing to be write onto file
if (f.length() == 0) {
ObjectOutputStream oos
= new ObjectOutputStream(fos);
oos.writeObject(c);
oos.close();
}
// There is content in file to be write on
else {
MyObjectOutputStream oos = null;
oos = new MyObjectOutputStream(fos);
oos.writeObject(c);
// Closing the FileOutputStream object
// to release memory resources
oos.close();
}
// Closing the File class object to avoid
// read-write
fos.close();
}
// Catch block to handle the exceptions
catch (Exception e) {
// Print the exception along with the
// display message
System.out.println("Error Occurred" + e);
}
// Change the flag status
status = true;
}
return status;
}
}
For now, save this code in a file CustomerCollection.java
Example 2: Customer.java
Java
// Java program of Customer.java
import java.io.*;
class Customer implements Serializable {
// Private class variables
private String name;
private long acc_No;
// Class Constructor
Customer(String n, long id)
{
acc_No = id;
name = n;
}
// Getter methods of class variables
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
// Java Program to illustrate Main.java
// Importing input output classes
import java.io.*;
// Main class
// Here all above helper classes comes into play
public class Main {
// Main driver method
public static void main(String[] args)
{
// Class objects assigned with constructors
// Customer input entries
Customer c1 = new Customer("Rita", 1);
Customer c2 = new Customer("Sita", 2);
// Adding new customers as created above
CustomerCollection.AddNewCustomer(c1);
CustomerCollection.AddNewCustomer(c2);
// Display message for better readability and
// understanding
System.out.println("****Reading File****");
// Lastly 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.
Similar Reads
How to Fix java.util.NoSuchElementException in Java?
An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Suppose if our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file
4 min read
StreamCorruptedException in Java
The class StreamCorruptedException of ObjectStreamException is an exception thrown when control information that was read from an object stream violates internal consistency checks. It will create a StreamCorruptedException and list a reason why the exception was thrown. If no parameters are passed
3 min read
java.io.UnsupportedEncodingException in Java with Examples
The java.io.UnsupportedEncodingException occurs when an unsupported character encoding scheme is used in java strings or bytes. The java String getBytes method converts the requested string to bytes in the specified encoding format. If java does not support the encoding format, the method String get
3 min read
Fix "java.lang.NullPointerException" in Android Studio
Hey Geeks, today we will see what NullPointerException means and how we can fix it in Android Studio. To understand NullPointerException, we have to understand the meaning of Null. What is null? "null" is a very familiar keyword among all the programmers out there. It is basically a Literal for Refe
4 min read
Java.io.SequenceInputStream in Java
The SequenceInputStream class allows you to concatenate multiple InputStreams. It reads data of streams one by one. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of fil
3 min read
How to Fix java.lang.classcastexception in Java?
ClassCastException in Java occurs when we try to convert the data type of entry into another. This is related to the type conversion feature and data type conversion is successful only where a class extends a parent class and the child class is cast to its parent class. Here we can consider parent c
6 min read
Java.io.OutputStream class in Java
This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Constructo
2 min read
Java.io.ObjectOutputStream Class in Java | Set 1
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. Only objects that support the java.io.Serializable in
9 min read
Java.io.StringReader class in Java
StringReader class in Java is a character stream class whose source is a string. It inherits Reader Class. Closing the StringReader is not necessary, it is because system resources like network sockets and files are not used. Let us check more points about StringReader Class in Java. Declare StringR
4 min read
Java.io.PipedInputStream class in Java
Pipes in IO provides a link between two threads running in JVM at the same time. So, Pipes are used both as source or destination. PipedInputStream is also piped with PipedOutputStream. So, data can be written using PipedOutputStream and can be written using PipedInputStream.But, using both threads
5 min read