String与Blob互转和file文件与Blob互转方式
作者:腻&爱
这篇文章主要介绍了String与Blob互转和file文件与Blob互转方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
Blob对字符串类型操作
String转换Blob
可以通过SerialBlob创建Blob对象,SerialBlob下有两个构造函数,如需创建Blob对象,可以使用 byte[] 类型,先把String转成byte[]再调用构造函数。


String 转换为byte[]
/**
* String 转 byte[]
* @param str 请求进入字符串
* @return 返回byte[] 数组
* @throws Exception 抛出错误
*/
public byte[] readStream(String str) throws Exception {
InputStream inStream=new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}byte[] 转为 SerialBlob
Blob blob=new SerialBlob(readStream(str))
Blob转换Sting
同理,Blob类型转换为String,就是反过来,先转换成byte[],再转换成String。
private String blobToString(Blob blob) throws Exception {
InputStream inStream=blob.getBinaryStream();
StringBuffer stringBuffer=new StringBuffer();
try {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
String str=new String(buffer, 0, len);
stringBuffer.append(str);
}
}catch (Exception e){
throw e;
}finally {
if(inStream!=null){
inStream.close();
}
if(stringBuffer.length()>0){
return stringBuffer.toString();
}else{
return null;
}
}
}File转Blob
可以把File文件先转换成byte[],再通过SerialBlob对象创建
File转为byte[]
这个方法试试示例,可以去网上找一下File转换byte[]流的方法
//这个方法只是示例,不推荐这样使用
public static byte[] getFileByte(File file) throws Exception {
byte[] data = null;
InputStream in = new FileInputStream(file);
data = new byte[in.available()];
in.read(data);
in.close();
return data;
}byte[] 转为 SerialBlob
Blob blob=new SerialBlob(readStream(str))
Blob转File
可以通过Blob转成InputStream,再通过读取的方式转成File

Blob转InputStream
InputStream in = blob.getBinaryStream()
InputStream转File
public void blobToFile(Blob blob,File file) throws Exception {
InputStream inStream=null;
OutputStream outStream=null;
try {
outStream = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[2048];
while ((bytesRead = inStream.read(buffer, 0, 2048)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
}catch (Exception e){
throw new Exception(e);
}finally {
if(outStream!=null){
outStream.close();
}
if(inStream!=null){
inStream.close();
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
