首页 > 编程语言 > 详细

使用Base64将字节数组编码成字符串,或者将字符串解码成字节数组

时间:2021-05-06 15:12:34      阅读:19      评论:0      收藏:0      [点我收藏+]

一、根据图片的url将图片读入字节输入流中,然后将字节输入流中的内容读取到字节数组中,再将字节数组通过Base64编码成字符串

Map resultMap = new HashMap();
            List<String> images = new ArrayList<>();
            //根据采购订单详细获取样本图片,转为字节流
            List<AttachFile> fileList = attachFileService.getFileList(inDetailId, "B_IN_DETAIL", "BIDSAMPLE_IMG");
            fileList.stream().forEach(file -> {
                String url = shareFile + "/" + file.getUploadPath() + "/" + file.getCompressedName();
                try (InputStream in = new BufferedInputStream(new FileInputStream(url))) {
                    byte[] srcBytes = new byte[in.available()];
                    in.read(srcBytes);
                    images.add(Base64.getEncoder().encodeToString(srcBytes));
                } catch (Exception e) {
                    log.error("图片转换流异常:" + e.getMessage());
                }
            });
            resultMap.put("IMAGES", images);
            return resultMap;

二、将JSON字符串转换成字节数组,然后将字节数组中的内容通过字节输出流写入文件中

//将字符串转换为byte数组
        byte[] bytes = Base64.getDecoder().decode(base64.trim());
        File file = new File(dir + "/" + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bos.write(bytes);
        if (bos != null) {
            bos.close();
        }
        if (fos != null) {
            fos.close();
        }

引入Base64:

import java.util.Base64

 

使用Base64将字节数组编码成字符串,或者将字符串解码成字节数组

原文:https://www.cnblogs.com/zwh0910/p/14734582.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!