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;
    }
}
