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

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

  1、byte[]=>Blobsql

  咱們能夠經過Hibernate提供的表態方法來實現如:數組

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

  2、Blob=>byte[]圖片

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

  /**get

  * 把Blob類型轉換爲byte數組類型input

  * @param blobit

  * @returnio

  */

  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();

  以上片斷可做爲讀者參考。

相關文章
相關標籤/搜索