Java 類型相互轉(zhuǎn)換byte[]類型,Blob類型詳細介紹
在我們的程序開發(fā)當中,經(jīng)常會用到j(luò)ava.sql.Blob、byte[]、InputStream之間的相互轉(zhuǎn)換,但在JDK的API當中,又沒有直接給我們提供可用的API,下面的程序片段主要就是實現(xiàn)它們之間互換的util.
一、byte[]=>Blob
我們可以通過Hibernate提供的表態(tài)方法來實現(xiàn)如:
org.hibernate.Hibernate.Hibernate.createBlob(new byte[1024]);
二、Blob=>byte[]
目前沒有找到好一點的API提供,所以只能自已來實現(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)換很簡單:InputStream is = new ByteArrayInputStream(new byte[1024]);
五、InputStream => Blob
可通過Hibernate提供的API:Hibernate.createBlob(new FileInputStream(" 可以為圖片/文件等路徑 "));
六、Blob => InputStream
Blog轉(zhuǎn)流,可通過提供的API直接調(diào)用:new Blob().getBinaryStream();
以上片段可作為讀者參考。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Java中如何快速構(gòu)建項目腳手架的實現(xiàn)
這篇文章主要介紹了Java中如何快速構(gòu)建項目腳手架,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05
Mybatis傳參為逗號分隔的字符串情形進行in條件查詢方式
這篇文章主要介紹了Mybatis傳參為逗號分隔的字符串情形進行in條件查詢方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
java eclipse 出現(xiàn) xxx cannot be resolved to a type 錯誤解決方法
這篇文章主要介紹了java eclipse 出現(xiàn) xxx cannot be resolved to a type 錯誤解決方法的相關(guān)資料,需要的朋友可以參考下2017-03-03

