Java type Mutual conversion byte[] type, blob type details _java

Source: Internet
Author: User

In our program development, we often use the Java.sql.Blob, byte[], inputstream between the conversion, but in the JDK API, not directly to provide us with the available APIs, the following pieces of the program is mainly to achieve the util between them.

First, Byte[]=>blob

We can use the hibernate provided by the attitude of the way to achieve such as:

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

  II, blob=>byte[]

There is no good API available at the moment, so you can only implement it yourself. Examples are as follows:

/**

* Converts a blob type to a byte array type

* @param blob

*

@return

/Private byte[] Blobtobytes (blob blob) {  c6/> 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;

}

}



 Third, inputstream=>byte[]

Private byte[] Inputstreamtobyte (InputStream is) throws IOException {bytearrayoutputstream

bytestream = new BYTEARR  Ayoutputstream ();

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

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

 Six, Blob => InputStream

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

The above fragments can be used as reference for readers.

Thank you for reading, I hope to help you, thank you for your support for this site!

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.