Home  >  Article  >  Java  >  Detailed explanation of the code to implement IO stream file encoding

Detailed explanation of the code to implement IO stream file encoding

Y2J
Y2JOriginal
2017-05-15 10:15:451621browse

This article introduces the method of java io stream file encoding through example code. It is very good and has reference value. Friends who need it can refer to it

•Encoding of files

package cn.test;
import java.io.UnsupportedEncodingException;
public class Demo15 {
  public static void main(String[] args) throws UnsupportedEncodingException {
    String str = "你好ABC123";
    byte[] b1 = str.getBytes();//转换成字节系列用的是项目默认的编码
    for (byte b : b1) {
      //把字节(转换成了int)以十六进制方式显示
      System.out.print(Integer.toHexString(b & 0xff) + " ");
    }
    System.out.println("");
    //utf8编码,中文占用3个字节,英文和数字占用1个字节
    byte[] b2 = str.getBytes("utf8");
    for (byte b : b2) {
      System.out.print(Integer.toHexString(b & 0xff) + " ");
    }
    System.out.println("");
    //gbk编码,中文占用两个字节,英文和数字占用1个字节
    byte[] b3 = str.getBytes("gbk");
    for (byte b : b3) {
      System.out.print(Integer.toHexString(b & 0xff) + " ");
    }
    System.out.println("");
    //java是双字节编码 utf-16be
    //utf-16be编码,中文占2个字节,英文和数字也占用2个字节
    byte[] b4 = str.getBytes("utf-16be");
    for (byte b : b4) {
      System.out.print(Integer.toHexString(b & 0xff) + " ");
    }
    System.out.println("");
    //当字节序列是某种编码时,这时候想把字节序列变成字符串,也需要用这种编码方式,否则会出现乱码
    String str1 = new String(b4);//使用项目默认的编码
    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
你好ABC123

A file is a byte sequence, which can be any encoded byte sequence.

If we create a text file directly on a Chinese machine, then the text file only recognizes ansi encoding (under the Chinese system, ansi encoding represents gbk encoding)

[Related recommendations]

1. Special recommendation: "php Programmer Toolbox" V0.1 version download

2. JavaFree Video Tutorial

3. YMP Online Manual

The above is the detailed content of Detailed explanation of the code to implement IO stream file encoding. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn