String 和 byte[]

时间:2023-03-08 22:34:53
String 和 byte[]

使用默认字符集合

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

public byte[] getBytes()

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

public String(byte bytes[])

默认字符集合

System.out.println(Charset.defaultCharset());

使用指定的字符集合

public byte[] getBytes(String charsetName)

Constructs a new String by decoding the specified array of bytes using the specified charset.

public String(byte bytes[], String charsetName)

字符集合不相同时会导致看到的字符串不一致,请确保字符集合相同。

小样:

byte[] bytes = "字符串".getBytes("utf-8");
System.out.println(new String(bytes,"utf-8"));// 字符串