导师给分配一个任务,需要将数据库A中的blob数据转换为Base64编码存进xml文件中,并且最后需要读取xml文件,将其中的base64字段转换回blob然后存放在新数据库B中,其中就设计Blob以及Base64的相互转换问题,将Blob转换为Base64还比较好解决,但是由Base64转回Blob废了很大的功夫,这里就分享一下我的具体方法;
//Blob转BASE64
public static String cvtBlobToBs64String(Blob in_blob) {
StringBuffer result = null;
String ls_result = "";
Base64.Encoder encoderBase64 = Base64.getEncoder();
if (null != in_blob) {
try {
InputStream msgCnt = in_blob.getBinaryStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer1 = new byte[2000];//每次读取2000个字节
int n = 0;
while (-1 != (n = msgCnt.read(buffer1))) {
output.write(buffer1, 0, n);
}
ls_result = encoderBase64.encodeToString(output.toByteArray());//编码
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return ls_result;
//return result;
} else {
return null;
}
}
将Base64转换回Blob无法直接转换,需要先将其转换为byte数组,然后再转换为Blob,其中需要用到hibernate这个jar包,这里只给出代码
//将base64编码转换为byte数组
public static byte[] transformBase64(String str) {
BASE64Decoder decode = new BASE64Decoder();
byte[] b = null;
try {
b = decode.decodeBuffer(str);
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
//将byte数组转换为blob对象
public static Blob fromByteArrayToBlob(byte[] bytes){
Configuration configure = new Configuration().configure();
SessionFactory sessionFactory = configure.buildSessionFactory();
Session session = sessionFactory.openSession();
Blob blob = session.getLobHelper().createBlob(bytes);
String string = cvtBlobToBs64String(blob);
System.out.println(string);
return blob;
}