Java 類型互相轉換byte[]類型,Blob類型具體引見。本站提示廣大學習愛好者:(Java 類型互相轉換byte[]類型,Blob類型具體引見)文章只能為提供參考,不一定能成為您想要的結果。以下是Java 類型互相轉換byte[]類型,Blob類型具體引見正文
在我們的法式開辟傍邊,常常會用到java.sql.Blob、byte[]、InputStream之間的互相轉換,但在JDK的API傍邊,又沒有直接給我們供給可用的API,上面的法式片斷重要就是完成它們之間交換的util.
1、byte[]=>Blob
我們可以經由過程Hibernate供給的亮相辦法來完成如:
org.hibernate.Hibernate.Hibernate.createBlob(new byte[1024]);
2、Blob=>byte[]
今朝沒有找到好一點的API供給,所以只能自已來完成。示例以下:
/**
* 把Blob類型轉換為byte數組類型
* @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;
}
}
}
3、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;
}
4、byte[]=> InputStream
byte[]到inputStream之間的轉換很簡略:InputStream is = new ByteArrayInputStream(new byte[1024]);
5、InputStream => Blob
可經由過程Hibernate供給的API:Hibernate.createBlob(new FileInputStream(" 可認為圖片/文件等途徑 "));
6、Blob => InputStream
Blog轉流,可經由過程供給的API直接挪用:new Blob().getBinaryStream();
以上片斷可作為讀者參考。
感激浏覽,願望能贊助到年夜家,感謝年夜家對本站的支撐!