Java类型相互转换byte[]类型,blob类型

在我们的程序开发当中,经常会用到java.sql.Blob、byte[]、InputStream之间的相互转换,但在JDK的API当中,又没有直接给我们提供可用的API,下面的程序片段主要就是实现它们之间互换的util.

一、byte[]=>Blob

我们可以通过Hibernate提供的表态方法来实现如:

org.hibernate.Hibernate.Hibernate.createBlob(new byte[1024]);

二、Blob=>byte[]

目前没有找到好一点的API提供,所以只能自已来实现。示例如下:

/**

* 把Blob类型转换为byte数组类型

* @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;

}

}

}

三、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;

}

四、byte[]=> InputStream

byte[]到inputStream之间的转换很简单:InputStream is = new ByteArrayInputStream(new byte[1024]);

五、InputStream => Blob

可通过Hibernate提供的API:Hibernate.createBlob(new FileInputStream(" 可以为图片/文件等路径 "));

六、Blob => InputStream

Blog转流,可通过提供的API直接调用:new Blob().getBinaryStream();

以上片段可作为读者参考。

                                                                                                   技术分享:www.kaige123.com

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,742评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,853评论 18 139
  • 一. Java基础部分.................................................
    wy_sure阅读 3,832评论 0 11
  • 很久没穿的羽绒服 压在橱柜的最深处 那一天我收拾衣服 它安静沉默不语 高三的某个夜晚 我们逛着服装店 用我的奖学金...
    宋予屿阅读 222评论 6 6
  • 刷新UITableView上的单个cell 刷新UITableView上的单个section
    诠释残缺阅读 917评论 0 5