package com.ema.common.utils;

import lombok.SneakyThrows;

import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;
/**
 * Base64工具类
 */
public class Base64Util {

    /**
     * File文件转换为base64编码字符串
     */
    @SneakyThrows
    public static String toStr(File file) {
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        byte[] bytes = Base64.getEncoder().encode(buffer);
        return new String(bytes);
    }

    /**
     * String转换为base64编码字符串
     */
    @SneakyThrows
    public static String toStr(String str) {
        byte[] bytes = Base64.getEncoder().encode(str.getBytes());
        return new String(bytes);
    }

    /**
     * base64字符串转换为byte[]
     */
    public static byte[] toBytes(String base64Str) {
        return Base64.getMimeDecoder().decode(base64Str);
    }

}
