IOUtils.toByteArray is returning empty byte array

2.2k Views Asked by At

I am new to Java development so apologies in advance if I am asking something stupid.

I am trying to retrieve an image and it's thumbnail from sql database. I get data from ResultSet in BinaryStream format and then convert it to byte[].

For thumbnail it works fine and for original image too I am able to retrieve BinaryStream using getBinaryStream method But when I convert it to byte[], the array remain empty for some reason.

binaryStream = rs.getBinaryStream("image");
thumbBinaryStream = rs.getBinaryStream("thumbnail");
if (binaryStream != null) {
    // Tested on following line and I get empty imageBytes
    byte[] imageBytes = IOUtils.toByteArray(binaryStream); 
    thisRecord.put("image", DatatypeConverter.printBase64Binary(imageBytes)); // imageBytes is empty here 
}
2

There are 2 best solutions below

4
On

To be sure: Statement and ResultSet must be closed and getBinaryStream only used when the ResultSet is still open, like:

try (ResultSet rs = stmt.executeQuery()) {
    while (rs.next()) {
        InputStream binaryStream = rs.getBinaryStream("image");
        InputStream thumbBinaryStream = rs.getBinaryStream("thumbnail");
        if (binaryStream != null) {
            // Tested on following line and I get empty imageBytes
            byte[] imageBytes = IOUtils.toByteArray(binaryStream); 
            thisRecord.put("image", DatatypeConverter.printBase64Binary(imageBytes));
            boolean mustGenerateThumbnail = thumbBinaryStream == null;
            if (mustGenerateThumbnail ) {
                thumbBinaryStream = generateThumbnail(imageBytes);
            }
            byte[] thumbBytes = IOUtils.toByteArray(thumbBinaryStream);
            thisRecord.put("thumbnail", DatatypeConverter.printBase64Binary(thumbBytes));

Here we are at the error. At this point thumbBinaryStream is read till the end, so do:

            if (mustGenerateThumbnail ) {
                ByteArrayInputStream baIn = new ByteArrayInputStream(thumbBytes);
                saveThumbnailForRecordWithId(baIn, floor_drawing_id);
            }
        }
    }
}

(Here I used try-with-resources to automatically close the ResultSet even on thrown exception.)

Furthermore there is a more general class for Base64. Should you in future have the need for such.

DatatypeConverter.printBase64Binary(thumbBytes)
Base64.getEncoder().encodeToString(thumbBytes)
3
On

We probably need more information, especially about the datatypes of the columns, but maybe it helps to retrieve the stream from the BLOB like in this example:

if (rs.getMetaData().getColumnType(column) == Types.BLOB) {
        in = rs.getBlob(column).getBinaryStream();
    } else {
        in = rs.getBinaryStream(column);
    }