繁体   English   中英

IOUtils.toByteArray返回空字节数组

[英]IOUtils.toByteArray is returning empty byte array

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

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

对于缩略图,它也可以正常工作,对于原始图像,我也可以使用getBinaryStream方法检索BinaryStream 但是当我将其转换为byte[]由于某种原因该数组仍为空

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 
}

我们可能需要更多信息,尤其是有关列的数据类型的信息,但也许像下面的示例那样,它有助于从BLOB检索流:

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM