【转帖】
在我们的程序开发当中,经常会用到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();
以上片段可作为读者参考。
相关推荐
[java]将Byte存入blob.rar
Blob、InputStream、byte 互转
主要介绍了Java 类型相互转换byte[]类型,Blob类型的相关资料,需要的朋友可以参考下
Delphi 如何将二维数组数据 以Blob 存入数据库中 并读取 。先将二维数组转换维流文件,以内存流 Blob 形式存入到数据库中。 读取时以流获取 然后读出到数组中
oracle中blob 字段类型的应用oracle中blob 字段类型的应用oracle中blob 字段类型的应用oracle中blob 字段类型的应用oracle中blob 字段类型的应用oracle中blob 字段类型的应用oracle中blob 字段类型的应用
Mybatis 处理 CLOB、BLOB 类型数据
Oralce 保存与读取Blob类型文件
NULL 博文链接:https://yuhuiblog695685688425687986842568269.iteye.com/blog/2229183
delphi读写BLOB字段delphi读写BLOB字段delphi读写BLOB字段delphi读写BLOB字段delphi读写BLOB字段delphi读写BLOB字段delphi读写BLOB字段delphi读写BLOB字段delphi读写BLOB字段delphi读写BLOB字段delphi读写BLOB字段...
java中sqllite数据库blob数据类型的存取.docx
Oracle SQL 函数进行BLOB转换Varchar2
最近开发遇到blob类型转换为String,一时犯难。所以总结了一段代码与之分享。亲测
SQLSERVER数据库中存储BLOB类型数据,在线等现在公司要求用PB6.5+SQLser
C# oracle blob类型 读入与保存
blob 类型写入数据库通过操作文件处理
mysql+Qt 下对blob数据类型操作
java读取大字段,介绍java如何读取大字段blob,解决程序员头疼问题
UTL_RAW.CAST_TO_VARCHAR2
PB中用OLE存取blob类型数据PB中用OLE存取blob类型数据PB中用OLE存取blob类型数据PB中用OLE存取blob类型数据PB中用OLE存取blob类型数据PB中用OLE存取blob类型数据PB中用OLE存取blob类型数据PB中用OLE存取blob类型数据
经典的上载图片,存到BLOB对象里面,附带读取图片