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

一、根据图片的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
原文地址:https://www.cnblogs.com/zwh0910/p/14734582.html