The first development environment I use is eclipse. Create a Java Project default encoding is GBK, as shown in figure:
Here is the specific code:
Import java.io.UnsupportedEncodingException; public class Demo1 {public static void main (string[] args) throws Unsupportedencodingexception {String s = "I love abc"
;
byte[] bytes1 = s.getbytes ("GBK");/does not write encoding, this String is encoded as a byte sequence using the platform's default character set, and returns to byte[]. S.getbytes (Charset Charset) encodes this string into a byte sequence using a given Charset;//Returns a byte[] byte array for (byte b:bytes1) {Sy
Stem.out.print (integer.tohexstring (B&0XFF) + ""); integer.tohexstring (int i) returns the string representation of an integer parameter in the form of a 16-in (cardinality 16) unsigned integer}//GBK encoding Chinese occupies two bytes, and 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 encoding Chinese occupies three bytes, English occupies a byte System.out.println ();
Java is a double-byte code--->utf-16be >> Chinese and English all 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 some sort of encoding, this time you want to turn the byte sequence into a * string, andNeed to use this type of encoding, otherwise garbled * * * * * * * SYSTEM.OUT.PRINTLN (); String str1 = new string (BYTES3);//The default encoding of the project (GBK encoding)----->> BYTES3 is defined above as "Utf-16be" code, so there will be garbled System.out.print
ln (STR1);
System.out.println ();
String str2 = new String (Bytes3, "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 the Chinese machine, then the text file only knows the ANSI encoding */}}
Results of Printing:
In general, the encoding must correspond, otherwise there will be garbled.