1 文件转base64
声明:我用的是Hutool的Base64下的api
package cn.hutool.core.codec;
首先找一张图片

很简单,直接使用Base64的encode方法就可以拿到文件的base64码:
	File file = new File("D:\\Tools\\Images\\北极熊.jpg");
	String encode = Base64.encode(file);
通过断点,可以看到附件的base64就是一串很长的字符串。

2 base64转文件
拿到附件的base64之后,就可以通过该方法进行转换为附件
/** 
     * @description base64转附件     
     * @date 17:17 2023/11/7
     * @param base64 附件的base64码
     * @param filePath 存储路径
     * @return java.io.File
    **/
    public static File base64ToFile(String base64, String filePath) {
        File file = new File(filePath);
        byte[] buffer;
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            buffer = base64Decoder.decodeBuffer(base64);
            FileOutputStream out = new FileOutputStream(filePath);
            out.write(buffer);
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return file;
    }
在本地新建文件夹

调用:

查看附件,以及通过base64保存到本地了:

参考代码
完整代码如下,供参考:
package com.test.HutoolTest;
import cn.hutool.core.codec.Base64;
import sun.misc.BASE64Decoder;
import java.io.File;
import java.io.FileOutputStream;
public class Base64Test {
    public static void main(String[] args){
        // 本地附件
        File file = new File("D:\\Tools\\Images\\大裤衩.jpg");
        String encode = Base64.encode(file);
        // base64转为附件
        base64ToFile(encode, "D:\\Tools\\Images\\base64ToFile\\"+file.getName());
    }
    /**
     * @description base64转附件
     * @date 17:17 2023/11/7
     * @param base64 附件的base64码
     * @param filePath 存储路径
     * @return java.io.File
    **/
    public static File base64ToFile(String base64, String filePath) {
        File file = new File(filePath);
        byte[] buffer;
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            buffer = base64Decoder.decodeBuffer(base64);
            FileOutputStream out = new FileOutputStream(filePath);
            out.write(buffer);
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return file;
    }
}



















![洛谷P1024 [NOIP2001 提高组] 一元三次方程求解(优雅的暴力+二分,干净利落)](https://img-blog.csdnimg.cn/ac019003e7714b9ebf996a71d60c68b0.jpeg)