Java類型相互轉換byte[]類型,blob類型

在我們的程序開發當中,經常會用到java.sql.Blob、byte[]、InputStream之間的相互轉換,但在JDK的API當中,又沒有直接給我們提供可用的API,下面的程序片段主要就是實現它們之間互換的util.

一、byte[]=>Blob

我們可以通過Hibernate提供的表態方法來實現如:

org.hibernate.Hibernate.Hibernate.createBlob(new byte[1024]);

二、Blob=>byte[]

目前沒有找到好一點的API提供,所以只能自已來實現。示例如下:

/**

* 把Blob類型轉換為byte數組類型

* @param blob

* @return

Advertisements

*/

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) {

Advertisements

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之間的轉換很簡單:InputStream is = new ByteArrayInputStream(new byte[1024]);

五、InputStream => Blob

可通過Hibernate提供的API:Hibernate.createBlob(new FileInputStream(" 可以為圖片/文件等路徑 "));

六、Blob => InputStream

Blog轉流,可通過提供的API直接調用:new Blob().getBinaryStream();

以上片段可作為讀者參考。

---這是一個能教你學會Java編程的微信公眾號:kaigexuetang_com(長按可複製關注)

Advertisements

你可能會喜歡