在 Java 開發中,處理二進制數據時經常需要在 byte[]、java.sql.Blob 和 InputStream 之間進行轉換。雖然 JDK 沒有直接提供現成的 API,但透過 Hibernate 或自行實現工具類即可輕鬆完成。本文整理六種常見轉換場景,提供可直接使用的代碼片段。
利用 Hibernate 提供的靜態方法:
Blob blob = org.hibernate.Hibernate.createBlob(byteArray);
需自行讀取 Blob 的二進制流:
private byte[] blobToBytes(Blob blob) {
try (BufferedInputStream is = new BufferedInputStream(blob.getBinaryStream())) {
byte[] bytes = new byte[(int) blob.length()];
int offset = 0, read;
while (offset < bytes.length && (read = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += read;
}
return bytes;
} catch (Exception e) {
return null;
}
}
使用 ByteArrayOutputStream 緩衝:
private byte[] inputStreamToByte(InputStream is) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
return baos.toByteArray();
}
}
直接用 ByteArrayInputStream 包裝:
InputStream is = new ByteArrayInputStream(byteArray);
同樣透過 Hibernate:
Blob blob = Hibernate.createBlob(new FileInputStream("文件路徑"));
直接呼叫 Blob 介面方法:
InputStream is = blob.getBinaryStream();
掌握這六種轉換模式,即可應付絕大多數二進制數據處理需求。建議將常用工具方法封裝到專案的 BlobUtils 類中,提高復用性。