Oct 01

Read the bytes from the Blob into a ByteArrayOutputStream.


ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];

InputStream in = blob.getBinaryStream();

int n = 0;
while ((n=in.read(buf))>=0)
{
   baos.write(buf, 0, n);

}

in.close();
byte[] bytes = baos.toByteArray(); 

written by objects \\ tags: , , ,


3 Responses to “How do I convert a JDBC Blob to a byte array?”

  1. Jodi Says:

    This worked for us in JDeveloper 10g, but now we are using 11g.
    The getBinaryStream method has been deprecated. The Blob is defined as weblogic.jdbc.vendor.oracle.OracleThinBlob, so now we have the getBinaryOutputStream() method instead. This means that the types are incompatible and that the blob cannot be read into a byte array.
    I have tried many methods, but cannot get this to work. Does anyone have an example?
    Thanks.

  2. objects Says:

    Where has it been deprecated?

  3. Jodi Says:

    Thank you for your response. I am new to Java and I was incorrect.
    Previously (in 10g) my blob was defined as:
    oracle.sql.BLOB blob = (oracle.sql.BLOB) stmt.getBlob(3);
    For 11g, that is changed to:
    OracleThinBlob blob = (OracleThinBlob) stmt.getBlob(3);

    I then was unable to compile due to getBinaryStream().
    InputStream inBlob = blob.getBinaryStream();

    I thought that OracleThinBlob was subclassing oracle.sql.Blob and that I’d just be able to use getBinaryStream(). It turns out that OracleThinBlob is an interface.
    I was able to solve my problem with a cast:
    InputStream inBlob = ((java.sql.Blob) blob).getBinaryStream();

Leave a Reply

You must be logged in to post a comment.