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!