java8 文件图片转base64 编码解码

base64 编码解码工具类 

import sun.misc.BASE64Encoder;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

public class Base64Util {

    /**
     * 文件转化成base64字符串
     */
    public static String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(new File(path));
            data = new byte[in.available()];
            in.read(data);
            in.close();
            System.out.println(base64);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }

    /**
     * 将base64转换为文件并存储到指定位置
     */
    public static boolean base64ToFile(String base64Str, String filePath) {
        if (base64Str == null && filePath == null) {
            return false;
        }
        try {
            Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64Str), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
    


}

 

    原文作者:Lion Li
    原文地址: https://blog.csdn.net/weixin_40461281/article/details/81740375
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞