字节与字符的转换
1. 字节转换为字符
方式一:String(byte[] bytes) 通过使用平台的默认字符集解码指定的字节数组来构造新的 String 。
public class Main {
public static void main(String[] args) {
String s="my name is Mike";
byte[] bytes=s.getBytes();
for(int i=0;i<bytes.length;i++) {
System.out.print(bytes[i]+"\t");
}
System.out.println();
String a=new String(bytes);
System.out.println(a);
}
}
方式二:String(byte[] bytes, Charset charset) 构造一个新的String由指定用指定的字节的数组解码charset 。
public class Main {
public static void main(String[] args) throws UnsupportedEncodingException {
String s="my name is Mike 你好";
byte[] bytes=s.getBytes();
for(int i=0;i<bytes.length;i++) {
System.out.print(bytes[i]+"\t");
}
System.out.println();
String string=new String(bytes,"GBK");//一定要抛出UnsupportedEncodingException异常
System.out.println(string);
}
}
2. 字符转换为字节
方式一:getBytes()方法
public class Main {
public static void main(String[] args) {
String s="my name is Mike";
byte[] bytes=s.getBytes();
for(int i=0;i<bytes.length;i++) {
System.out.print(bytes[i]+"\t");
}
}
}
方式·二:getBytes(Charset charset) 使用给定的charset将该String编码为字节序列,将结果存储到新的字节数组中。
public class Main {
public static void main(String[] args) throws UnsupportedEncodingException {
String s="my name is Mike 你好";
byte[] bytes=s.getBytes("utf-8");
for(int i=0;i<bytes.length;i++) {
System.out.print(bytes[i]+"\t");
}
}
}
3. 字符与字节通过编码方式来转换,主要有以下几种编码方式:utf-8、GBK、Unicode、ASCII
各种编码方式下,字符与字节的对应关系
1. utf-8
一个英文字母(不分大小写)占一个字节的空间,一个中文汉字占三个字节的空间。
2. GBK
一个英文占一个字节,一个中文汉字占两个字节。
3. ASCII
一个英文字母(不分大小写)占一个字节的空间,一个中文汉字占两个字节的空间。
4. Unicode
一个英文字母占两个字节的空间,一个中文汉字占两个字节的空间。
英文标点占一个字节,中文标点占两个字节。