java實現(xiàn)文件和base64相互轉(zhuǎn)換
1.文件轉(zhuǎn)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轉(zhuǎn)文件
拿到附件的base64之后,就可以通過該方法進(jìn)行轉(zhuǎn)換為附件
/**
* @description base64轉(zhuǎn)附件
* @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;
}
在本地新建文件夾

調(diào)用:

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

3.參考代碼
完整代碼如下,供參考:
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轉(zhuǎn)為附件
base64ToFile(encode, "D:\\Tools\\Images\\base64ToFile\\"+file.getName());
}
/**
* @description base64轉(zhuǎn)附件
* @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;
}
}
以上就是java實現(xiàn)文件和base64相互轉(zhuǎn)換的詳細(xì)內(nèi)容,更多關(guān)于java文件和base64相互轉(zhuǎn)換的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringBoot集成Aviator實現(xiàn)參數(shù)校驗的示例代碼
在實際開發(fā)中,參數(shù)校驗是保障系統(tǒng)穩(wěn)定和數(shù)據(jù)可靠性的重要措施,Aviator 是一個高性能的表達(dá)式引擎,它能夠簡化復(fù)雜的邏輯判斷并提升參數(shù)校驗的靈活性,本文將介紹如何在 Spring Boot 中集成 Aviator,并利用它來實現(xiàn)靈活的參數(shù)校驗,需要的朋友可以參考下2025-02-02
Java線程重復(fù)執(zhí)行以及操作共享變量的代碼示例
這篇文章主要介紹了Java中對線程重復(fù)執(zhí)行以及操作共享變量的代碼示例,來自于Java面試題目的練習(xí)整理,需要的朋友可以參考下2015-12-12
SpringBoot 靜態(tài)資源導(dǎo)入及首頁設(shè)置問題
本節(jié)了解一下 SpringBoot 中 Web 開發(fā)的靜態(tài)資源導(dǎo)入和首頁設(shè)置,對應(yīng) SpringBoot-03-Web 項目,本節(jié)主要是從源碼的角度,研究了一下靜態(tài)資源導(dǎo)入和首頁設(shè)置的問題2021-09-09
java基于正則提取字符串中的數(shù)字功能【如提取短信中的驗證碼】
這篇文章主要介紹了java基于正則提取字符串中的數(shù)字功能,可用于提取短信中的驗證碼,涉及java基于正則的字符串匹配相關(guān)操作技巧,需要的朋友可以參考下2017-01-01
SpringBoot兩種方式接入DeepSeek的實現(xiàn)
本文主要介紹了SpringBoot兩種方式接入DeepSeek的實現(xiàn),包括HttpClient方式和基于spring-ai-openai的方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-03-03
Java中Dijkstra算法求解最短路徑的實現(xiàn)
Dijkstra算法是一種解決最短路徑問題的常用算法,本文主要介紹了Java中Dijkstra算法求解最短路徑的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2023-09-09

