Java-IO stream file encoding and javaio stream Encoding
Package cn. test; import java. io. unsupportedEncodingException; public class Demo15 {public static void main (String [] args) throws UnsupportedEncodingException {String str = "Hello ABC123"; byte [] b1 = str. getBytes (); // convert to byte series using the project's default encoding for (byte B: b1) {// convert the byte (converted to int) display System in hexadecimal format. out. print (Integer. toHexString (B & 0xff) + "");} System. out. println (""); // utf8 encoding. Chinese occupies 3 bytes, and English and numbers occupy 1 byte [] b2 = str. getBytes ("utf8"); for (byte B: b2) {System. out. print (Integer. toHexString (B & 0xff) + "");} System. out. println (""); // gbk encoding. Chinese occupies two bytes. English and numbers occupy one byte [] b3 = str. getBytes ("gbk"); for (byte B: b3) {System. out. print (Integer. toHexString (B & 0xff) + "");} System. out. println (""); // java is double byte encoding utf-16be // utf-16be encoding, Chinese occupies 2 bytes, English and numbers also occupy 2 bytes byte [] b4 = str. getBytes ("utf-16be"); for (byte B: b4) {System. out. print (Integer. toHexString (B & 0xff) + "");} System. out. println (""); // This encoding method is also required when you want to convert a byte sequence into a string when the byte sequence is encoded, otherwise, garbled String str1 = new String (b4); // use the default project code System. out. println (str1); String str2 = new String (b4, "utf-16be"); System. out. println (str2 );}}
Execution result:
E4 bd a0 e5 a5 bd 41 42 43 31 32 33 e4 bd a0 e5 a5 bd 41 42 43 31 32 33 c4 e3 ba c3 41 42 43 31 32 33 4f 60 59 7d 0 41 0 42 0 43 0 31 0 32 0 33 O 'y} ABC123 Hello ABC123
A text file is a byte sequence, which can be any encoded byte sequence.
If we create a text file directly on a Chinese machine, this text file only recognizes ansi encoding (in a Chinese system, ansi encoding stands for gbk encoding)