1. 程式人生 > >byte陣列轉換為String字串

byte陣列轉換為String字串

平時經常會使用Bytes.toString(byte[] b)這種方法,但是這個是Hbase自帶的Bytes工具類,一旦離開Hbase的依賴那麼只能自己寫個工具類來轉換了,於是乎想到將Hbase的Bytes中部分方法提出來寫成自己的工具類,畢竟大牛寫的程式碼還是很信賴的,於是就產生了下面的工具類:

public class StrUtil {
    private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");

    public static String toString(byte[] b) {
        return b == null ? null : toString(b, 0, b.length);
    }

    public static String toString(byte[] b1, String sep, byte[] b2) {
        return toString(b1, 0, b1.length) + sep + toString(b2, 0, b2.length);
    }

    public static String toString(byte[] b, int off) {
        if (b == null) {
            return null;
        } else {
            int len = b.length - off;
            return len <= 0 ? "" : new String(b, off, len, UTF8_CHARSET);
        }
    }

    public static String toString(byte[] b, int off, int len) {
        return b == null ? null : (len == 0 ? "" : new String(b, off, len, UTF8_CHARSET));
    }
}