将Base64编码转换为Blob对象

导师给分配一个任务,需要将数据库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;
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值