您当前的位置: 首页 >  Java

梁云亮

暂无认证

  • 3浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

基于Java8的Base64Util工具类

梁云亮 发布时间:2021-05-18 10:03:36 ,浏览量:3

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;

/**
 * 在org.springframework.util包中有一个有同样功能的类:Base64Utils
 */
public class Base64Util {
    public Base64Util() {
    }

    /**
     * 功能:编码字符串
     *
     * @param data 源字符串
     * @return String
     * @author jiangshuai
     */
    public static String encode(String data) {
        return new String(encode(data.getBytes()));
    }

    /**
     * 功能:解码字符串
     *
     * @param data 源字符串
     * @return String
     * @author jiangshuai
     */
    public static String decode(String data) {
        return new String(decode(data.toCharArray()));
    }


    /**
     * 功能:编码byte[]
     *
     * @param data 源
     * @return char[]
     * @author jiangshuai
     */
    public static char[] encode(byte[] data) {
        char[] out = new char[((data.length + 2) / 3) * 4];
        for (int i = 0, index = 0; i  shift) & 0xff);
                }
            }
        }

        // if there is STILL something wrong we just have to throw up now!
        if (index != out.length) {
            throw new Error("Miscalculated data length (wrote " + index
                    + " instead of " + out.length + ")");
        }

        return out;
    }

    /**
     * 功能:编码文件
     *
     * @param file 源文件
     * @author jiangshuai
     */
    public static void encode(File file) throws IOException {
        if (!file.exists()) {
            System.exit(0);
        } else {
            byte[] decoded = readBytes(file);
            char[] encoded = encode(decoded);
            writeChars(file, encoded);
        }
        file = null;
    }

    /**
     * 功能:解码文件。
     *
     * @param file 源文件
     * @throws IOException
     * @author jiangshuai
     */
    public static void decode(File file) throws IOException {
        if (!file.exists()) {
            System.exit(0);
        } else {
            char[] encoded = readChars(file);
            byte[] decoded = decode(encoded);
            writeBytes(file, decoded);
        }
        file = null;
    }

    private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
    private static byte[] codes = new byte[256];

    static {
        for (int i = 0; i             
关注
打赏
1665409997
查看更多评论
0.0578s