吃透Shiro源码8----String Byte[]互转

技术手法

(1)String、char[]、byte[]数组三者互转

String转为byte[],可以按照不同的编码格式转为字节数组。

    public static byte[] toBytes(String source, String encoding) throws CodecException {
        try {
            return source.getBytes(encoding);
        } catch (UnsupportedEncodingException e) {
            throw new CodecException("字符串转为字节数组出错", e);
        }
    }

byte[]转为String

public static String toString(byte[] bytes, String encoding) throws CodecException {

        try {
            return new String(bytes, encoding);
        } catch (Exception e) {
            throw new CodecException("字节数字组转为字符串出错", e);
        }
    }

char[]转为String再转为byte[]

    public static byte[] toBytes(char[] chars) {
        //char数组为字符串
        String source = new String(chars);
        return toBytes(source);
    }

byte[]转为String再转为char[]

    public static char[] toChars(byte[] bytes, String encoding) throws CodecException {
        String originSource = toString(bytes, encoding);
        return originSource.toCharArray();
    }
posted @ 2022-07-17 12:14  小大宇  阅读(18)  评论(0编辑  收藏  举报