String与Blob互转 和 file文件与Blob互转
最编程
2024-02-25 11:41:36
...
项目中使用大文本,或者是存文件可以使用Blob,这样方便存取,不影响现有的项目代码逻辑
这里写目录标题
- Blob对字符串类型操作
- String转换Blob
- String 转换为byte[]
- byte[] 转为 SerialBlob
- Blob转换Sting
- File转Blob
- File转为byte[]
- byte[] 转为 SerialBlob
- Blob转File
- Blob转InputStream
- InputStream转File
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();
}
}
}