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