Base64与文件流之间的相互转换

文件流转换成Base64

复制代码
 /**
     * 文件流转换成Base4
     */
    public String fileToBase64(String path){
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes=new byte[(int)file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }
复制代码

Base64转换成文件流

复制代码
  /**
     * Base64解码成File文件
     */
    public static void base64ToFile(String base64,String fileName){
        File file = null;
        //创建文件目录
        String filePath = "C:\\Users\\hemanman6\\Desktop";
        File dir = new File(filePath);
        if(!dir.exists()&& !dir.isDirectory()){
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        byte[] bytes = Base64.getDecoder().decode(base64);
        file = new File(filePath+"\\"+fileName);
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
复制代码

转自:https://blog.csdn.net/qq_38530648/article/details/121562484

posted @   丹阳89  阅读(1927)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示