Home>

•File 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 ();
    for (byte b:b1) {
      //The byte (converted to int) is displayed in hexadecimal
      system.out.print (integer.tohexstring (b&0xff) + "");
    }
    system.out.println ("");
    //utf8 encoding, Chinese takes 3 bytes, English and numbers take 1 byte
    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 1 byte
    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 takes 2 bytes, English and numbers also take 2 bytes
    byte [] b4=str.getbytes ("utf-16be");
    for (byte b:b4) {
      system.out.print (integer.tohexstring (b&0xff) + "");
    }
    system.out.println ("");
    //When the byte sequence is some kind of encoding,At this time, I want to turn the byte sequence into a string.
You also need to use this encoding method,Otherwise there will be garbled characters
    string str1=new string (b4);//Use the project's default encoding
    system.out.println (str1);
    string str2=new string (b4, "utf-16be");
    system.out.println (str2);
  }
}

Results of the:

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
Hi abc123

File is a sequence of bytes,Can be any sequence of encoded bytes.

If we create a text file directly on a Chinese machine,Then the text file only knows ansi encoding (under Chinese system,ansi encoding stands for gbk encoding)

  • Previous C # operation ftp class complete example
  • Next Detailed installation of docker ce on Ubuntu1610