string和byte类型互相转换

1.string 转 byte[]

//为UTF8编码
String str = "hello java";
byte[] bytes=str.getBytes("UTF8");

2.byte[]转string

String srt2=new String(bytes,"UTF-8");

注意:一定要注意转换时的编码问题,尤其byte转string时一定要指定编码,否则很容易出现中文乱码问题。
对于指定编码,在StandardCharsets类里面有他的编码集:

System.out.println(new String(b_ISO88591, StandardCharsets.UTF_8));

源码如下:

public final class StandardCharsets {
    
    

    private StandardCharsets() {
    
    
        throw new AssertionError("No java.nio.charset.StandardCharsets instances for you!");
    }
    /**
     * Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the
     * Unicode character set
     */
    public static final Charset US_ASCII = Charset.forName("US-ASCII");
    /**
     * ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
     */
    public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
    /**
     * Eight-bit UCS Transformation Format
     */
    public static final Charset UTF_8 = Charset.forName("UTF-8");
    /**
     * Sixteen-bit UCS Transformation Format, big-endian byte order
     */
    public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
    /**
     * Sixteen-bit UCS Transformation Format, little-endian byte order
     */
    public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
    /**
     * Sixteen-bit UCS Transformation Format, byte order identified by an
     * optional byte-order mark
     */
    public static final Charset UTF_16 = Charset.forName("UTF-16");
}

猜你喜欢

转载自blog.csdn.net/m0_37899908/article/details/118947330