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 (); |