我有一个来自其他系统的字节数组,该字符串在编码后应该与英文、日文和中文字符混合,我该如何处理它?谢谢!
//the byte[] represents "C注ファイル PARM 年月日输入不正确 入力文字列"
byte[] buf = new byte[] { 64, 64, 64, 64, 64, -61, 14, 73, 68, 67, -97,
67, 71, 67, -126, 67, -81, 15, 64, 64, 64, 64, 64, 64, 64, 64,
64, -41, -63, -39, -44, 64, 14, 82, -23, 90, -63, 84, -44, 85,
-29, 84, -22, 73, -70, 91, -98, 84, -74, 15, 64, 64, 64, 64,
64, 64, 64, 64, 64, 14, 70, 101, 69, -9, 69, -54, 72, -14, 75,
-76, 15, 64, 64, 64, 64, 64, 64, 64, 64, 64 };
String japaneseStr = new String(buf,"cp939");// convert to japanese
System.out.println(japaneseStr);//output:" C注ファイル PARM 衷扞唖詑煤証昿翰 入力文字列 "
String chineseStr = new String(buf,"cp935"); // convert to chinese
System.out.println(chineseStr); //output:" C堡ファイル PARM 年月日输入不正确 ㄅ㈦⑹绑兜 "
//"注ファイル" is japanese
//"年月日输入不正确" is chinese
//"入力文字列" is japanese
//i want to get the result is " C注ファイル PARM 年月日输入不正确 入力文字列 "
最佳答案
字符所属的语言并不重要。重要的是原始字符串如何编码为结果字节数组。
您可以使用以下 String
构造函数将字节数组解码为 String
:
String(byte[] bytes, String charsetName)
String(byte[] bytes, Charset charset)
您可以将字节数组传递给 String
的构造函数并提供字符集(通过名称或作为 Charset
对象,请参阅 StandardCharsets
中的常量)。
例如,如果原始字符串是使用 UTF-8 字符编码进行编码的,您可以像这样解码它:
String str = new String(source, "UTF-8");
或者:
String str = new String(source, StandardCharsets.UTF_8);
您的示例:
如果您的源代码确实使用 UTF-8 进行编码,它将如下所示:
byte[] source = {-26, -75, -117, -24, -81, -107, -26, -107, -120, -26, -98, -100,
97, 98, 99, 100, 101, -26, -106, -80, -25, -108, -97, -25, -108, -93, -25,
-82, -95, -25, -112, -122, -29, -126, -73, -29, -126, -71, -29, -125, -122,
-29, -125, -96}
以下代码:
String str = new String(source, StandardCharsets.UTF_8);
System.out.println(str);
打印:
测试效果abcde新生産管理システム
关于java - 如何在Java中以混合编码将字节数组编码为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27008398/