以下为字符串转为GBK编码
String s = in.nextLine();
byte b[]=s.getBytes("GBK");
for(byte b1:b){
System.out.print(b1+" ");
}
以下为字符串转为UTF-8编码
String s = in.nextLine();
byte b[]=s.getBytes("UTF-8");
for(byte b1:b){
System.out.print(b1+" ");
}
那么该如何由GBK编码得到相应的字节呢
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();//输入-60 -29 -70 -61
String code[]=str1.split("\\s+");//以空格为分隔符的数组
byte b[]=new byte[code.length];//创建字节数组
for(int i=0;i<code1.length;i++){
b[i]=Integer.valueOf(code1[i]).byteValue(); //将每个字节都存放在byte b中
}
String gbk=new String(b,"GBK");//将字节以GBK编码输出
System.out.println(gbk); //猜猜看输出的是什么内容?
}
}
同样还可以输入-28 -67 -96 -27 -91 -67
String gbk=new String(b,“UTF-8”);