java base64

  • A+
所属分类:Java 未分类 软件开发
package com.rome.recruit.domain.util;

import jodd.util.StringUtil;
import sun.misc.BASE64Decoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author yangsea
 */
public class Base64Util {

    private Base64Util(){

    }
    public static String fileToBase64(String path) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64();
        return new String(encoder.encode(data));
    }

    public static String webFileToBase64(String path){
        byte[] data = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try{
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            in = connection.getInputStream();
            out = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while((len =in.read(b)) != -1){
                out.write(b,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(in != null ){
                    in.close();
                }
            }catch (IOException e){
                e.getStackTrace();
            }
        }
        org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64();
        return new String(encoder.encode(out.toByteArray()));
    }

    public static boolean base64ToFile(String base,String path){
        if(StringUtil.isBlank(base)){
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try{
            byte[] bytes = decoder.decodeBuffer(base);
            for(int i = 0;i < bytes.length; ++i){
                if(bytes[i] < 0){
                    bytes[i]+=256;
                }
            }
            out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(out != null){
                    out.close();
                }
            }catch (IOException e){
                e.getStackTrace();
            }
        }
        return true;
    }

    //对照表
//    private static String base64hash = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-/";
    private static String base64hash = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
//    javascript
//    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    public static String encode(String src){
        StringBuilder result = new StringBuilder();
        byte[] bytes = src.getBytes();
        int length = bytes.length;
        int mod = 0;
        byte prev = 0;
        for(int i=0;i<length;i++){
            mod = i%3;
            if(mod==0){
                result.append(base64hash.charAt((bytes[i] >> 2) & 0x3F));
            }else if(mod==1){
                result.append(base64hash.charAt((prev << 4 | bytes[i] >> 4  &0x0F )& 0x3F));
            }else{
                result.append(base64hash.charAt((bytes[i] >> 6 & 0x03 | prev << 2) & 0x3F));
                result.append(base64hash.charAt(bytes[i] & 0x3F));
            }
            prev = bytes[i];
        }
        if(mod==0){
            result.append(base64hash.charAt(prev << 4 & 0x3C));
            result.append("==");
        }else if(mod==1){
            result.append(base64hash.charAt(prev << 2 & 0x3F));
            result.append("=");
        }
        return result.toString();
    }

    public static String decode(String src){
        if(StringUtil.isBlank(src)){
            return "";
        }
        byte temp = 0;
        String result = "";
        for(int i=0;i<src.length();i++){
            temp = (byte) base64hash.indexOf(src.charAt(i));
            if(temp==-1){
                result+="000000";
            }else{
                String t = Integer.toBinaryString(temp);
                if(t.length()==7){
                    t = t.substring(1);
                }else if(t.length()==8){
                    t = t.substring(2);
                }
                while(t.length()<6){
                    t = "0"+t;
                }
                result+=t;
            }
        }
        while(result.endsWith("00000000")){
            result = result.substring(0,result.length()-8);
        }
        byte[] bytes = new byte[result.length()/8];
        for(int i=0;i<bytes.length;i++){
            bytes[i]= Integer.valueOf(result.substring(i*8,(i+1)*8),2).byteValue();
        }
        return new String(bytes);
    }

    public static void main(String[] args) {

//        APP平台运营总监(J10988)
//        System.out.println(decode("QVBQ5bmz5Y+w6L+Q6JCl5oC755uRKEoxMDk4OCk="));
        System.out.println(new String(new String(Base64.getDecoder().decode("QVBQ5bmz5Y+w6L+Q6JCl5oC755uRKEoxMDk4OCk=")).getBytes(StandardCharsets.UTF_8)));
        System.out.println(decode("QVBQ5bmz5Y+w6L+Q6JCl5oC755uRKEoxMDk4OCk="));
        System.out.println(encode("APP平台运营总监(J10988)"));
    }

}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: