Search code examples
javaobjectinputstreameofexception

EOFException Runtime Error while dealing with SealedObject


I am currently experimenting with the encryption and decryption of objects but I am stumbling upon an EOFException every time my read method is declared. I feel like there is a lot of redundancy within my code trying to deal with all of the exceptions so it would be great if you could tell which catch/throw phrases to remove and how I can resolve this problem. Thanks.

java.io.EOFException points to the line in my code with (** **). All the other lines are NetBeans generated code.

public static void readFromBinary() throws IllegalBlockSizeException, EOFException
{
try {
    BufferedReader br3 = new BufferedReader(new FileReader(noteFileName));     
    if (br3.readLine() != null) {
        FileInputStream fINoteStream = new FileInputStream(noteFileName);
        ObjectInputStream oINoteStream = new ObjectInputStream(fINoteStream);
        while(true){
        try{
        **SealedObject sObj = (SealedObject)oINoteStream.readObject();**
        Note note = (Note) sObj.getObject(new NullCipher());
        noteList.add(note);
        }
        catch(EOFException e){
            e.printStackTrace();
            break;
        }
        catch (IllegalBlockSizeException e){
            e.printStackTrace();
            break;
        }
        catch (BadPaddingException e){
            e.printStackTrace();
            break;
        }
        catch (ClassNotFoundException e){
            e.printStackTrace();
            break;
        }
        }
        oINoteStream.close();
    }
}
catch (FileNotFoundException e){
    e.printStackTrace();
}
catch (IOException e){
    e.printStackTrace();
} 
}
}

Method Call in another class:

try{
        DataStorage.readFromBinary();
        }
        catch (IllegalBlockSizeException e)
        {
            e.printStackTrace();
        }
        catch (EOFException e)
        {
            e.printStackTrace();
        }

Solution

  • EOFException just means you got to the end of the input. You need to close the inout and break out of the loop. You don't need to print the stack trace. It doesn't have anything to do with SealedObject specifically, just with how object streams work.

    You need to decide whether you're catching this exception or throwing it. You shouldn't do both.