PackageCom.io; Public classEncodedemo { Public Static voidMain (string[] args)throwsexception{//TODO auto-generated Method StubString s = "China abc"; byte[] bytes1 = S.getbytes ();//convert to byte sequence with project default byte encoding for(byteb:bytes1) { //converts bytes to int to be displayed in 16 binary modeSystem.out.print (integer.tohexstring (B&0XFF) + ""); } System.out.println (); byte[] Bytes2 = S.getbytes ("GBK"); //GBK Code Chinese occupies 2 bytes, English occupies 1 bytes for(byteb:bytes2) { //converts bytes to int to be displayed in 16 binary modeSystem.out.print (integer.tohexstring (B&0XFF) + ""); } System.out.println (); byte[] Bytes3 = S.getbytes ("Utf-8"); //utf-8 Code Chinese occupies 3 bytes, English occupies 1 bytes for(byteB:bytes3) { //converts bytes to int to be displayed in 16 binary modeSystem.out.print (integer.tohexstring (B&0XFF) + ""); } //Java is a two-byte encoding utf-16be//utf-16be Chinese occupies 2 bytes, English occupies 2 bytesSystem.out.println (); byte[] bytes4 = S.getbytes ("Utf-16be"); //utf-8 Code Chinese occupies 3 bytes, English occupies 1 bytes for(byteb:bytes4) { //converts bytes to int to be displayed in 16 binary modeSystem.out.print (integer.tohexstring (B&0XFF) + ""); } System.out.println (); /** When your byte sequence is some kind of encoding, this time you want to turn the byte sequence into a * string, also need to use this encoding method, no one will appear garbled*/String str1=NewString (BYTES4); System.out.println (STR1); String str2=NewString (Bytes4, "Utf-16be"); System.out.println (STR2); /** text file is a byte sequence * can be any encoded byte sequence * If we create a text file directly on a Chinese machine * Then the text file only knows the ANSI code * Unicom, United This is a coincidence, they just fit the rules of Utf-8 coding*/ } }
Coding problems with Java files