• 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);
        }
    }
  • 相关阅读:
    有一个双重模板化的错误实现
    非类型模板参数
    C++模板
    初始化列表initializer_list
    C++类型转换
    const引用和constexpr
    逆元
    卡特兰数
    最短路问题
    Android打印机效果的闪屏
  • 原文地址:https://www.cnblogs.com/yanjy/p/16193792.html
Copyright © 2020-2023  润新知