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 ByteArray InputStream(new byte[1024]).
5. InputStream => Blob
Hibernate를 통해 제공되는 API: Hibernate.createBlob(new File InputStream("이미지/파일 등 경로 가능");
6. Blob = > InputStream
Blog 트랜스퍼, 제공된 API를 통해 직접 호출 가능: new Blob().getBinaryStream();
상기 단편은 독자로 참고할 수 있다.
읽어주셔서 감사합니다. 여러분에게 도움이 되었으면 좋겠습니다. 본 사이트에 대한 지지에 감사드립니다!

좋은 웹페이지 즐겨찾기