最近碰到了Java.sql.Blob、byte[]、InputStream三种类型的相互转换的问题,这里总结一下:
一、InputStream ---> Blob
Hibernate提供了一个API:Hibernate.createBlob(new FileInputStream(" image/file path "));
二、Blob ---> InputStream
Blog本身有一个API:new Blob().getBinaryStream();
三、byte[ ] ---> Blob
Hibernate提供的API:org.hibernate.Hibernate.Hibernate.createBlob(new byte[1024]);
四、Blob ---> byte[ ]
/**
*Bolg to byte[]
*
*/
private byte[] BlobToBytes(Blob blob) {
BufferedInputStream bufferedInputStream = null;
try {
//利用Blob自带的一个函数去将blob转换成InputStream
bufferedInputStream = new BufferedInputStream(blob.getBinaryStream());
//申请一个字节流,长度和blob相同
byte[] bytes = new byte[(int) blob.length()];
int len = bytes.length;
int offset = 0;
int read = 0;
while (offset < len//确保不会读过头
&& (read = bufferedInputStream.read(bytes, offset, len - offset)) >= 0) {
//BufferedInputStream内部有一个缓冲区,默认大小为8M,每次调用read方法的时候,它首先尝试从缓冲区里读取数据,
//若读取失败(缓冲区无可读数据),则选择从物理数据源(譬如文件)读取新数据(这里会尝试尽可能读取多的字节)放入到缓冲区中,
//最后再将缓冲区中的内容部分或全部返回给用户
//也就是说read函数一次性可能读不完,所以可能会分多次读,于是就有了上面的逻辑
offset += read;
}
return bytes;
} catch (Exception e) {
return null;
} finally {
try {
bufferedInputStream.close();
} catch (IOException e) {
return null;
}
}
}
五、InputStream ---> byte[ ]
/**
*InputStream to byte[]
*
*/
private byte[] InputStreamToByte(InputStream inputstream) throws IOException {
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
//public abstract int read() throws IOException
//从(来源)输入流中(读取的内容)读取数据的下一个字节到(去处)java程序内部中
//返回值为0到255的int类型的值,返回值为字符的ACSII值
//如果没有可用的字节,因为已经到达流的末尾, -1返回的值
//运行一次只读一个字节,所以经常与while((len = inputstream.read()) != -1)一起使用
int letter;
while ((letter = inputstream.read()) != -1) {
bytestream.write(letter);
}
byte imgdata[] = bytestream.toByteArray();
bytestream.close();
return imgdata;
}
六、byte[ ] ---> InputStream
byte[ ]转换为InputStream:InputStream is = new ByteArrayInputStream(new byte[1024]);