0

I have stored object in binary format in mysql db blob datatype, But now when I am reading it from the database I am getting following exception

java.io.StreamCorruptedException: invalid stream header: EFBFBDEF

I don't know how to solve this exception,

Could you please help me to solve this ?

class Book implements Serializable{ String name;

public Book(String name) {
    super();
    this.name = name;
}

public Book() {
    super();
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public byte[] getByteArray() throws IOException{
    ByteArrayOutputStream  bout  = new ByteArrayOutputStream();
    ObjectOutputStream     out   = new ObjectOutputStream(bout);
    out.writeObject(this);
    out.flush();
    out.close();
    return bout.toByteArray();
}

@Override
public String toString() {

    return "Book [name=" + name + "]";
}

}

public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "testApplicationContext.xml"});
        DataSource ds = (DataSource) context.getBean("dataSource");
        JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

        //Writing To DB
        int[] dataTypes = new int[1];
        dataTypes[0] = Types.BLOB;

        Object[] bindingValues = new Object[1];

        Book book = new Book("Demo String");

        bindingValues[0] = book.getByteArray();
        jdbcTemplate.update("insert into test values (NULL, ? )" , bindingValues, dataTypes);


        //Reading from DB
        SqlRowSet queryForRowSet = jdbcTemplate.queryForRowSet("select pattern from test");

        queryForRowSet.next();
        byte[] bytes = (byte[]) queryForRowSet.getObject(1);

        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);

        ObjectInputStream in = new ObjectInputStream(bi);

        System.out.println(in.readObject());

    }

Above code works if I insert new object and read it, But for existing object from DB I am getting the exception.

Thanks

Alpesh Jikadra
  • 1,692
  • 3
  • 18
  • 38

0 Answers0