First of all, the development environment I use is Eclipse. Create a java project default encoding is GBK, as shown in the figure::
The following is the specific code:
Import java.io.unsupportedEndEncodingException; Public Class Demo1 {Public Static Void Main (String [] ARGS) Throws UNSUPPORTEDEEXCEPTION {str ing s = "I love abc"; byte [] bytes1 = s.getbytes ("gbk"); // No Write the encoding, use the default character set of the platform to encode this String into a Byte sequence, and return byte []. //S.getBytes (Charset Charset) Use the given to the Byte sequence; // The return of It is a byte [] byte array for (byte b: bytes1) {System.out.print (Integer.Tohexstring (B & 0XFF)+""); //integer.tohexstring (InT I) with hexadecimal (base 16 16 ) Non -symbolic integer form returns a string of an integer parameter string representation} // gbk coding Chinese occupies two bytes, English occupies a byte System.out.println (); byte [] bytes2 = s.getbytes ("UTF -8 "); for (byte B: bytes2) {System.out.print (Integer.Tohexstring (B & 0xff)+" ");} // UTF-8 Coding Chinese possess three bytes in English, English occupies a byte SYSTEM .out.println (); // java is a double-byte encoding ---> UTF-16be >> Chinese and English occupy two bytes byte [] bytes3 = s.getbytes ("UTF-16BE"); for (byte b: bytes3) {System.out.print (Integer.Tohexstring (B & 0xff)+"");} /*When your byte sequence is a certain code, at this time, the byte sequence is turned into*characters String, you also need to use this encoding method, otherwise you will appear garbled * * */system.out.println (); String Str1 = New String (bytes3); // Use the default encoding of the project (GBK encoding) ------------------------------------------------------------------------------------------------------- ->> bytes3 is encoded as "UTF-16BE" above, so the garbled System.out.println (STR1); System.out.println (); String Str2 = New String (bytes3, "UTF-16BE 16BE "); System.out.println (STR2); /** text file is byte sequence* can be an arbitrarily encoded byte sequence* If we directly create text files on Chinese machines, then the text file only knows ANSI encoding only ANSI encoding * */}}
The result of printing:
In general, the encoding must be corresponding, otherwise there will be garbled.