StreamCorruptedException in Java
Last Updated :
05 Aug, 2022
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 in the constructor, then it will create a StreamCorruptedException and list no reason why the exception was thrown.
Syntax:
public StreamCorruptedException(String reason)
Parameters: reason – “String” describing the reason for the exception
Example 1:
Java
import java.io.*;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StreamCorruptedException;
class GFG {
public static void main(String[] args) throws Exception
{
InputStream in = new FileInputStream( "testout.txt" );
DataInputStream dis = new DataInputStream(in);
try {
if (dis.readByte() != 1 ) {
throw new StreamCorruptedException(
"File format not recognised" );
}
}
catch (StreamCorruptedException e) {
System.out.println(e);
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
java.io.StreamCorruptedException: File format not recognised
Now dwelling on the second example where file format is recognized. It is as follows for which go through below sample note below prior to implementation.
Note: Make the C098.txt file in the same folder of the program and copy the following fragment as it is. It is an example corrupted file
C098.txt
’ sr Product L desct Ljava / lang / String;
L priceq ~ L
productIdq ~ xpt Bookt Rs .200t P001’ sr
Product L desct Ljava / lang / String; L
priceq ~ L productIdq ~ xpt Laptopt Rs .45, 500t P087
Example 2:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws Exception
{
String CId = "C098.txt" ;
File objFile1 = new File(CId);
try {
FileInputStream objFIS
= new FileInputStream(objFile1);
ObjectInputStream objI
= new ObjectInputStream(objFIS);
Object obj = null ;
}
catch (StreamCorruptedException ex) {
System.out.println(
"Stream Corrupted Exception Occurred" );
}
catch (Exception e) {
System.out.println( "Hello" );
}
}
}
|
Output:
Stream Corrupted Exception Occurred
Share your thoughts in the comments
Please Login to comment...