In our program development, we often use the mutual conversion between java.sql.Blob, byte[], and InputStream, but in the JDK API, we do not directly provide us with available APIs. The following program fragments mainly implement the interchangeable util between them.
1. byte[]=>Blob
We can implement the statement method provided by Hibernate, such as:
org.hibernate.Hibernate.Hibernate.createBlob(new byte[1024]);
2. Blob=>byte[]
At present, no better API is found, so I can only implement it myself. 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; } } }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[] to inputStream is simple: InputStream is = new ByteArrayInputStream(new byte[1024]);
5. InputStream => Blob
API that can be provided through Hibernate: Hibernate.createBlob(new FileInputStream("can be a path for pictures/files, etc."));
6. Blob => InputStream
Blog transfer, which can be called directly through the provided API: new Blob().getBinaryStream();
The above clips can be used as a reference for readers.
Thank you for reading, I hope it can help you. Thank you for your support for this site!