package com.jkcredit.invoice.util;

import org.apache.commons.codec.binary.Base64;

import java.io.*;

public class Base64Util {
    public static void main(String [] args){
        System.out.print(fileToBase64("d:/123.pdf"));
    }
    public static String fileToBase64(String path) {
        int byteread = 0;
        String total = null;
        byte[] totalbyte = new byte[0];
        InputStream inStream = null;
        try {
            inStream = getStream(path);
            byte[] buffer = new byte[1024];
            while ((byteread = inStream.read(buffer)) != -1) {
                //拼接流，这样写是保证文件不会被篡改
                totalbyte = byteMerger(totalbyte, buffer, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inStream) inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Base64.encodeBase64String(totalbyte);
    }

    //合并数组
    public static byte[] byteMerger(byte[] totalArr, byte[] mergerArr, int mergerLen) {
        if (null == totalArr || null == mergerArr) return totalArr;
        if (mergerLen == 0 || mergerLen > mergerArr.length) {
            throw new RuntimeException("mergerLen : " + mergerArr + " ,mergerArrLen : " + mergerArr.length);
        }
        int len = totalArr.length;
        byte[] reArr = new byte[len + mergerLen];
        System.arraycopy(totalArr, 0, reArr, 0, len);
        System.arraycopy(mergerArr, 0, reArr, len, mergerLen);
        return reArr;
    }

    //根据 url 获取输入流
    public static InputStream getStream(String path) throws IOException {
        File file = new File(path);
        InputStream in = new FileInputStream(file);
        return in;
    }



    /**
     * 精确计算base64字符串文件大小（单位：B）
     * @param base64String
     * @return
     */
    public static double base64FileSize(String base64String) {
        /**检测是否含有base64,文件头)*/
        if (base64String.lastIndexOf(",") > 0) {
            base64String = base64String.substring(base64String.lastIndexOf(",")+1);
        }
        /** 获取base64字符串长度(不含data:audio/wav;base64,文件头) */
        int size0 = base64String.length();
        /** 获取字符串的尾巴的最后10个字符，用于判断尾巴是否有等号，正常生成的base64文件'等号'不会超过4个 */
        String tail = base64String.substring(size0 - 10);
        /** 找到等号，把等号也去掉,(等号其实是空的意思,不能算在文件大小里面) */
        int equalIndex = tail.indexOf("=");
        if (equalIndex > 0) {
            size0 = size0 - (10 - equalIndex);
        }
        /** 计算后得到的文件流大小，单位为字节 */
        return size0 - ((double) size0 / 8) * 2;
    }

}
