Java type Mutual conversion byte[] type, blob type

Source: Internet
Author: User

In our program development, often use JAVA.SQL.BLOB, byte[], inputstream between the mutual conversion, but in the JDK API, not directly to provide us with the API available, the following program fragment is mainly to achieve their exchange between the util.

First, Byte[]=>blob

We can use the gesture method provided by hibernate to achieve the following:

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

II, blob=>byte[]

There is no better API available at this point, so it can only be implemented by itself. Examples are as follows:

/**

* Convert blob type to byte array type

* @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;

}

}

}

Three, 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;

}

Iv. byte[] = InputStream

The conversion between byte[] to InputStream is simple: inputstream is = new Bytearrayinputstream (new byte[1024]);

V. InputStream = Blob

API:Hibernate.createBlob available through Hibernate (new FileInputStream ("can be a picture/file path"));

VI. BLOB = InputStream

The blog stream can be called directly via the provided API: New Blob (). Getbinarystream ();

The above fragments can be used as readers ' reference.

Technology sharing: www.kaige123.com

Java type Mutual conversion byte[] type, blob type

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.