Packagecn.test;Importjava.io.UnsupportedEncodingException; Public classDEMO15 { Public Static voidMain (string[] args)throwsunsupportedencodingexception {String str= "Hello ABC123"; byte[] B1 = Str.getbytes ();//Convert to Byte series with project default encoding for(byteb:b1) { //the byte (converted to int) is displayed in 16 binary modeSystem.out.print (integer.tohexstring (b & 0xff) + ""); } System.out.println (""); //UTF8 encoding, Chinese occupies 3 bytes, English and digits occupy 1 bytes byte[] B2 = str.getbytes ("UTF8"); for(byteb:b2) {System.out.print (integer.tohexstring (b& 0xff) + ""); } System.out.println (""); //GBK encoding, Chinese occupies two bytes, English and digits occupy 1 bytes byte[] B3 = Str.getbytes ("GBK"); for(byteb:b3) {System.out.print (integer.tohexstring (b& 0xff) + ""); } System.out.println (""); //Java is a two-byte encoding utf-16be//UTF-16BE encoding, Chinese accounts for 2 bytes, English and numbers also occupy 2 bytes byte[] B4 = str.getbytes ("Utf-16be"); for(byteb:b4) {System.out.print (integer.tohexstring (b& 0xff) + ""); } System.out.println (""); //when the byte sequence is some kind of encoding, this time want to turn the byte sequence into a string, also need to use this encoding method, otherwise there will be garbledString str1 =NewString (B4);//using the project default encodingSystem.out.println (STR1); String str2=NewString (B4, "utf-16be"); System.out.println (STR2); }}
Execution Result:
E4 BD A0 e5 A5 bd , e4 BD A0 e5 a5 bd c4 e3 Ba C3 4f , 7d 0, 0 0 0 to 0 0 O ' y}abc123 Hello ABC123
A text file is a sequence of bytes, which can be any encoded sequence of bytes.
If we create a text file directly on the Chinese machine, then the text file only knows the ANSI encoding (the ANSI code on the Chinese system is GBK encoded)
Encoding of the Java-io stream file