在我們的程序開(kāi)發(fā)當(dāng)中,經(jīng)常會(huì)用到j(luò)ava.sql.Blob、byte[]、InputStream之間的相互轉(zhuǎn)換,但在JDK的API當(dāng)中,又沒(méi)有直接給我們提供可用的API,下面的程序片段主要就是實(shí)現(xiàn)它們之間互換的util.
一、byte[]=>Blob
我們可以通過(guò)Hibernate提供的表態(tài)方法來(lái)實(shí)現(xiàn)如:
org.hibernate.Hibernate.Hibernate.createBlob(new byte[1024]);
二、Blob=>byte[]
目前沒(méi)有找到好一點(diǎn)的API提供,所以只能自已來(lái)實(shí)現(xiàn)。示例如下:
/**
* 把Blob類型轉(zhuǎn)換為byte數(shù)組類型
* @param blob
* @return
*/
private byte[] blobToBytes(Blob blob) {
BufferedInputStream is = null;
try {
is = new BufferedInputStream(blob.getBinaryStream());
byte[] bytes = new byte[(int) blob.length()];
int len = bytes.length;
int offset = 0;
int read = 0;
while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {
offset += read;
}
return bytes;
} catch (Exception e) {
return null;
} finally {
try {
is.close();
is = null;
} catch (IOException e) {
return null;
}
}
}
三、InputStream=>byte[]
private byte[] InputStreamToByte(InputStream is) throws IOException {
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1) {
bytestream.write(ch);
}
byte imgdata[] = bytestream.toByteArray();
bytestream.close();
return imgdata;
}
四、byte[] => InputStream
byte[]到inputStream之間的轉(zhuǎn)換很簡(jiǎn)單:InputStream is = new ByteArrayInputStream(new byte[1024]);
五、InputStream => Blob
可通過(guò)Hibernate提供的API:Hibernate.createBlob(new FileInputStream(" 可以為圖片/文件等路徑 "));
六、Blob => InputStream
Blog轉(zhuǎn)流,可通過(guò)提供的API直接調(diào)用:new Blob().getBinaryStream();
以上片段可作為讀者參考。
聯(lián)系客服