IOUtils.toByteArray返回空字节数组

时间:2018-07-10 14:30:46

标签: java sql arrays binarystream ioutils

我是Java开发的新手,因此如果我要问一些愚蠢的事情,请提前道歉。

我正在尝试从sql数据库中检索图像及其缩略图。 我从ResultSetBinaryStream格式获取数据,然后将其转换为byte[]

对于缩略图,它也可以很好地工作,并且对于原始图像,我也可以使用BinaryStream方法检索getBinaryStream,但是当我将其转换为byte[]时,,< strong>由于某种原因数组保持为空。

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 个答案:

答案 0 :(得分:0)

我们可能需要更多信息,尤其是有关列的数据类型的信息,但也许有助于从BLOB中检索流,如本例所示:

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

答案 1 :(得分:0)

要确保: 必须关闭Statement和ResultSet,并且getBinaryStream仅在ResultSet仍处于打开状态时使用,例如:

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));

这是我们的错误。此时,thumbBinaryStream将被读取到最后,因此:

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

(这里我使用try-with-resources即使在抛出异常时也自动关闭ResultSet。)

此外,Base64还有一个更通用的类。您将来是否应该有此需要。

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