Blob, inputstream, and byte Conversion

Source: Internet
Author: User

Blob, inputstream, and byte Conversion

 

Java is often used in our program development. SQL. blob, byte [], and inputstream are mutually converted. However, in JDK APIs, no available APIs are provided directly, the following program snippets mainly implement util interchange between them.

1. byte [] => blob

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

Org. hibernate. createblob (New byte [1, 1024]);

2. Blob => byte []

At present, there is no better API provision, so it can only be implemented by itself. Example:

/**
* Convert blob type to byte array type
* @ Param blob
* @ Return
*/
Private byte [] blobtobytes (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

The conversion between byte [] and inputstream is simple: inputstream is = new bytearrayinputstream (New byte [1024]);


5. inputstream => blob

APIS provided by hibernate: hibernate. createblob (New fileinputstream ("can be an image/file path "));

6. Blob => inputstream

Blog streaming, which can be called directly through the provided API: new Blob (). getbinarystream ();

 

 

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.