java實現(xiàn)文件和base64相互轉換
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保存到本地了:
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轉為附件 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; } }
以上就是java實現(xiàn)文件和base64相互轉換的詳細內容,更多關于java文件和base64相互轉換的資料請關注腳本之家其它相關文章!
相關文章
SpringBoot集成Aviator實現(xiàn)參數(shù)校驗的示例代碼
在實際開發(fā)中,參數(shù)校驗是保障系統(tǒng)穩(wěn)定和數(shù)據(jù)可靠性的重要措施,Aviator 是一個高性能的表達式引擎,它能夠簡化復雜的邏輯判斷并提升參數(shù)校驗的靈活性,本文將介紹如何在 Spring Boot 中集成 Aviator,并利用它來實現(xiàn)靈活的參數(shù)校驗,需要的朋友可以參考下2025-02-02java基于正則提取字符串中的數(shù)字功能【如提取短信中的驗證碼】
這篇文章主要介紹了java基于正則提取字符串中的數(shù)字功能,可用于提取短信中的驗證碼,涉及java基于正則的字符串匹配相關操作技巧,需要的朋友可以參考下2017-01-01SpringBoot兩種方式接入DeepSeek的實現(xiàn)
本文主要介紹了SpringBoot兩種方式接入DeepSeek的實現(xiàn),包括HttpClient方式和基于spring-ai-openai的方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-03-03Java中Dijkstra算法求解最短路徑的實現(xiàn)
Dijkstra算法是一種解決最短路徑問題的常用算法,本文主要介紹了Java中Dijkstra算法求解最短路徑的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2023-09-09