Base64与文件的互相转换

应用场景:

1丶对接第三方接口时, 接收回传参数时
2丶业务需要将base64保存
3丶给别人传参时

文件转base64:
// filePath 为文件所在全路径: D://file.txt
public static String getFileStr(String filePath) {

        //定义输出流对象
        InputStream in = null;
        byte[] data = null;
        // 读取文件字节数组
        try {
            in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert in != null;
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回 Base64 编码过的字节数组字符串
        assert data != null;
        return encoder.encode(data);
    }
base64转文件
// base64FileStr  base字符串
// filePath 同上
public static boolean generateFile(String base64FileStr, String filePath) {

        // 数据为空
        if (base64FileStr == null) {
            return false;
        }
        //判断文件夹是否存在
        File outputFile = new File(filePath);
        File fileP = outputFile.getParentFile();
        if (!fileP.exists() && !fileP.mkdirs() && !fileP.mkdir()) {
            throw new IllegalArgumentException("创建文件目录失败");
        }
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            // Base64解码,对字节数组字符串进行Base64解码并生成文件
            byte[] byt = decoder.decodeBuffer(base64FileStr);
            for (int i = 0, len = byt.length; i < len; ++i) {
                // 调整异常数据
                if (byt[i] < 0) {
                    byt[i] += 256;
                }
            }
            InputStream input = new ByteArrayInputStream(byt);
            // 生成指定格式的文件
            out = new FileOutputStream(filePath);
            byte[] buff = new byte[1024];
            int len;
            while ((len = input.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert out != null;
                out.flush();
                out.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }
结语:

欢迎留言交流, 谢谢!

猜你喜欢

转载自blog.csdn.net/spring_is_coming/article/details/108379942