我可以将String转换为Array作为UTF-8,但是我不能像第一个String那样将它转换回String.
public static void main(String[] args) {
Scanner h = new Scanner(System.in);
System.out.println("INPUT : ");
String stringToConvert = h.nextLine();
byte[] theByteArray = stringToConvert.getBytes();
System.out.println(theByteArray);
theByteArray.toString();
String s = new String(theByteArray);
System.out.println(""+s);
}
Run Code Online (Sandbox Code Playgroud)
如何打印theByteArray
为字符串?
Joe*_*Joe 12
String s = new String(theByteArray);
Run Code Online (Sandbox Code Playgroud)
应该真的
String s = new String(theByteArray, Charset.forName("UTF-8"));
Run Code Online (Sandbox Code Playgroud)
这里的根本问题是String构造函数不聪明.String构造函数无法区分正在使用的字符集,并尝试使用系统标准(通常类似于ASCII或ISO-8859-1)对其进行转换.这就是为什么普通的A-Za-z看起来很合适,但其他一切都开始失败了.
byte是从-127到127的类型,因此对于UTF-8转换,连续的字节需要连接.String构造函数不可能将其与字节数组区分开来,因此默认情况下它将单独处理每个字节(因此,为什么基本的字母数字将始终工作,因为它们属于此范围).
例:
String text = "?????";
byte[] array = text.getBytes("UTF-8");
String s = new String(array, Charset.forName("UTF-8"));
System.out.println(s); // Prints as expected
String sISO = new String(array, Charset.forName("ISO-8859-1")); // Prints 'ããã«ã¡ã¯'
System.out.println(sISO);
Run Code Online (Sandbox Code Playgroud)