fileToBase64互转

file和base64互转
package com.base64;

import java.io.*;
import java.util.Base64;

/**
 * file和base64互转
 */
public class Base64Util {
    /**
     * file转base64
     *
     * @param filePath 文件路径
     * @return
     */
    public static String fileToBase64(String filePath) {
        FileInputStream is = null;
        String base64 = "";
        try {
            File file = new File(filePath);
            is = new FileInputStream(file);
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
            byte[] encode = Base64.getEncoder().encode(buffer);
            base64 = new String(encode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return base64;
    }

    /**
     * base64转file
     *
     * @param base64
     * @param fileName 存储路径
     */
    private static void base64ToFile(String base64, String fileName) {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decode = decoder.decode(base64);
        FileOutputStream os = null;
        try {
            File file = new File(fileName);
            os = new FileOutputStream(fileName);
            os.write(decode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String base64 = fileToBase64("E:\\pic.png");
        System.out.println(base64);
        String fileName = "E:\\pic2.png";
        base64ToFile(base64, fileName);
    }
}

 

posted @ 2022-04-26 10:42  厚我  阅读(638)  评论(0编辑  收藏  举报