import java.io.UnsupportedEncodingException;
public class test {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "hello world";
byte[] bytes = str.getBytes("UTF8");
System.out.println("bytes= "+bytes);
String srt2=new String(bytes,"UTF-8");
System.out.println("srt2= "+srt2);
}
}
运行结果:

String 转换成 byte[] :string.getBytes("UTF8") *string 指字符串
byte[] 转换成 String :new String(bytes,"UTF-8") *bytes 指字节数组
本文介绍如何使用Java实现字符串与字节数组之间的相互转换。通过具体代码示例展示了利用getBytes方法将字符串转换为指定编码的字节数组,以及如何通过构造函数将字节数组还原为字符串。

3万+

被折叠的 条评论
为什么被折叠?



