可以肯定的是: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)